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,227
Replace CngCommon hash with OneShotHashHelpers
The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
vcsjones
2022-03-05T00:49:31Z
2022-03-05T03:49:08Z
94480f128c8af3e728b2b6e5ad2b13370f97b8f1
eb57c1276add1ec7e35897bfdbbebb648839dee3
Replace CngCommon hash with OneShotHashHelpers. The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
./src/coreclr/jit/eeinterface.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 EEInterface XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ // ONLY FUNCTIONS common to all variants of the JIT (EXE, DLL) should go here) // otherwise they belong in the corresponding directory. #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) #pragma warning(push) #pragma warning(disable : 4701) // difficult to get rid of C4701 with 'sig' below /*****************************************************************************/ /***************************************************************************** * * Filter wrapper to handle exception filtering. * On Unix compilers don't support SEH. */ struct FilterSuperPMIExceptionsParam_eeinterface { Compiler* pThis; Compiler::Info* pJitInfo; bool hasThis; size_t siglength; CORINFO_SIG_INFO sig; CORINFO_ARG_LIST_HANDLE argLst; CORINFO_METHOD_HANDLE hnd; const char* returnType; const char** pArgNames; EXCEPTION_POINTERS exceptionPointers; }; const char* Compiler::eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd) { const char* className; const char* methodName = eeGetMethodName(hnd, &className); if ((eeGetHelperNum(hnd) != CORINFO_HELP_UNDEF) || eeIsNativeMethod(hnd)) { return methodName; } FilterSuperPMIExceptionsParam_eeinterface param; param.returnType = nullptr; param.pThis = this; param.hasThis = false; param.siglength = 0; param.hnd = hnd; param.pJitInfo = &info; size_t length = 0; unsigned i; /* Generating the full signature is a two-pass process. First we have to walk the components in order to assess the total size, then we allocate the buffer and copy the elements into it. */ /* Right now there is a race-condition in the EE, className can be nullptr */ /* initialize length with length of className and '.' */ if (className) { length = strlen(className) + 1; } else { assert(strlen("<NULL>.") == 7); length = 7; } /* add length of methodName and opening bracket */ length += strlen(methodName) + 1; bool success = eeRunWithSPMIErrorTrap<FilterSuperPMIExceptionsParam_eeinterface>( [](FilterSuperPMIExceptionsParam_eeinterface* pParam) { /* figure out the signature */ pParam->pThis->eeGetMethodSig(pParam->hnd, &pParam->sig); // allocate space to hold the class names for each of the parameters if (pParam->sig.numArgs > 0) { pParam->pArgNames = pParam->pThis->getAllocator(CMK_DebugOnly).allocate<const char*>(pParam->sig.numArgs); } else { pParam->pArgNames = nullptr; } unsigned i; pParam->argLst = pParam->sig.args; for (i = 0; i < pParam->sig.numArgs; i++) { var_types type = pParam->pThis->eeGetArgType(pParam->argLst, &pParam->sig); switch (type) { case TYP_REF: case TYP_STRUCT: { CORINFO_CLASS_HANDLE clsHnd = pParam->pThis->eeGetArgClass(&pParam->sig, pParam->argLst); // For some SIMD struct types we can get a nullptr back from eeGetArgClass on Linux/X64 if (clsHnd != NO_CLASS_HANDLE) { const char* clsName = pParam->pThis->eeGetClassName(clsHnd); if (clsName != nullptr) { pParam->pArgNames[i] = clsName; break; } } } FALLTHROUGH; default: pParam->pArgNames[i] = varTypeName(type); break; } pParam->siglength += strlen(pParam->pArgNames[i]); pParam->argLst = pParam->pJitInfo->compCompHnd->getArgNext(pParam->argLst); } /* add ',' if there is more than one argument */ if (pParam->sig.numArgs > 1) { pParam->siglength += (pParam->sig.numArgs - 1); } var_types retType = JITtype2varType(pParam->sig.retType); if (retType != TYP_VOID) { switch (retType) { case TYP_REF: case TYP_STRUCT: { CORINFO_CLASS_HANDLE clsHnd = pParam->sig.retTypeClass; if (clsHnd != NO_CLASS_HANDLE) { const char* clsName = pParam->pThis->eeGetClassName(clsHnd); if (clsName != nullptr) { pParam->returnType = clsName; break; } } } FALLTHROUGH; default: pParam->returnType = varTypeName(retType); break; } pParam->siglength += strlen(pParam->returnType) + 1; // don't forget the delimiter ':' } // Does it have a 'this' pointer? Don't count explicit this, which has the this pointer type as the first // element of the arg type list if (pParam->sig.hasThis() && !pParam->sig.hasExplicitThis()) { assert(strlen(":this") == 5); pParam->siglength += 5; pParam->hasThis = true; } }, &param); if (!success) { param.siglength = 0; } /* add closing bracket and null terminator */ length += param.siglength + 2; char* retName = getAllocator(CMK_DebugOnly).allocate<char>(length); /* Now generate the full signature string in the allocated buffer */ if (className) { strcpy_s(retName, length, className); strcat_s(retName, length, ":"); } else { strcpy_s(retName, length, "<NULL>."); } strcat_s(retName, length, methodName); // append the signature strcat_s(retName, length, "("); if (param.siglength > 0) { param.argLst = param.sig.args; for (i = 0; i < param.sig.numArgs; i++) { var_types type = eeGetArgType(param.argLst, &param.sig); strcat_s(retName, length, param.pArgNames[i]); param.argLst = info.compCompHnd->getArgNext(param.argLst); if (i + 1 < param.sig.numArgs) { strcat_s(retName, length, ","); } } } strcat_s(retName, length, ")"); if (param.returnType != nullptr) { strcat_s(retName, length, ":"); strcat_s(retName, length, param.returnType); } if (param.hasThis) { strcat_s(retName, length, ":this"); } assert(strlen(retName) == (length - 1)); return (retName); } #pragma warning(pop) #endif // defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) /*****************************************************************************/
// 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 EEInterface XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ // ONLY FUNCTIONS common to all variants of the JIT (EXE, DLL) should go here) // otherwise they belong in the corresponding directory. #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) #pragma warning(push) #pragma warning(disable : 4701) // difficult to get rid of C4701 with 'sig' below /*****************************************************************************/ /***************************************************************************** * * Filter wrapper to handle exception filtering. * On Unix compilers don't support SEH. */ struct FilterSuperPMIExceptionsParam_eeinterface { Compiler* pThis; Compiler::Info* pJitInfo; bool hasThis; size_t siglength; CORINFO_SIG_INFO sig; CORINFO_ARG_LIST_HANDLE argLst; CORINFO_METHOD_HANDLE hnd; const char* returnType; const char** pArgNames; EXCEPTION_POINTERS exceptionPointers; }; const char* Compiler::eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd) { const char* className; const char* methodName = eeGetMethodName(hnd, &className); if ((eeGetHelperNum(hnd) != CORINFO_HELP_UNDEF) || eeIsNativeMethod(hnd)) { return methodName; } FilterSuperPMIExceptionsParam_eeinterface param; param.returnType = nullptr; param.pThis = this; param.hasThis = false; param.siglength = 0; param.hnd = hnd; param.pJitInfo = &info; size_t length = 0; unsigned i; /* Generating the full signature is a two-pass process. First we have to walk the components in order to assess the total size, then we allocate the buffer and copy the elements into it. */ /* Right now there is a race-condition in the EE, className can be nullptr */ /* initialize length with length of className and '.' */ if (className) { length = strlen(className) + 1; } else { assert(strlen("<NULL>.") == 7); length = 7; } /* add length of methodName and opening bracket */ length += strlen(methodName) + 1; bool success = eeRunWithSPMIErrorTrap<FilterSuperPMIExceptionsParam_eeinterface>( [](FilterSuperPMIExceptionsParam_eeinterface* pParam) { /* figure out the signature */ pParam->pThis->eeGetMethodSig(pParam->hnd, &pParam->sig); // allocate space to hold the class names for each of the parameters if (pParam->sig.numArgs > 0) { pParam->pArgNames = pParam->pThis->getAllocator(CMK_DebugOnly).allocate<const char*>(pParam->sig.numArgs); } else { pParam->pArgNames = nullptr; } unsigned i; pParam->argLst = pParam->sig.args; for (i = 0; i < pParam->sig.numArgs; i++) { var_types type = pParam->pThis->eeGetArgType(pParam->argLst, &pParam->sig); switch (type) { case TYP_REF: case TYP_STRUCT: { CORINFO_CLASS_HANDLE clsHnd = pParam->pThis->eeGetArgClass(&pParam->sig, pParam->argLst); // For some SIMD struct types we can get a nullptr back from eeGetArgClass on Linux/X64 if (clsHnd != NO_CLASS_HANDLE) { const char* clsName = pParam->pThis->eeGetClassName(clsHnd); if (clsName != nullptr) { pParam->pArgNames[i] = clsName; break; } } } FALLTHROUGH; default: pParam->pArgNames[i] = varTypeName(type); break; } pParam->siglength += strlen(pParam->pArgNames[i]); pParam->argLst = pParam->pJitInfo->compCompHnd->getArgNext(pParam->argLst); } /* add ',' if there is more than one argument */ if (pParam->sig.numArgs > 1) { pParam->siglength += (pParam->sig.numArgs - 1); } var_types retType = JITtype2varType(pParam->sig.retType); if (retType != TYP_VOID) { switch (retType) { case TYP_REF: case TYP_STRUCT: { CORINFO_CLASS_HANDLE clsHnd = pParam->sig.retTypeClass; if (clsHnd != NO_CLASS_HANDLE) { const char* clsName = pParam->pThis->eeGetClassName(clsHnd); if (clsName != nullptr) { pParam->returnType = clsName; break; } } } FALLTHROUGH; default: pParam->returnType = varTypeName(retType); break; } pParam->siglength += strlen(pParam->returnType) + 1; // don't forget the delimiter ':' } // Does it have a 'this' pointer? Don't count explicit this, which has the this pointer type as the first // element of the arg type list if (pParam->sig.hasThis() && !pParam->sig.hasExplicitThis()) { assert(strlen(":this") == 5); pParam->siglength += 5; pParam->hasThis = true; } }, &param); if (!success) { param.siglength = 0; } /* add closing bracket and null terminator */ length += param.siglength + 2; char* retName = getAllocator(CMK_DebugOnly).allocate<char>(length); /* Now generate the full signature string in the allocated buffer */ if (className) { strcpy_s(retName, length, className); strcat_s(retName, length, ":"); } else { strcpy_s(retName, length, "<NULL>."); } strcat_s(retName, length, methodName); // append the signature strcat_s(retName, length, "("); if (param.siglength > 0) { param.argLst = param.sig.args; for (i = 0; i < param.sig.numArgs; i++) { var_types type = eeGetArgType(param.argLst, &param.sig); strcat_s(retName, length, param.pArgNames[i]); param.argLst = info.compCompHnd->getArgNext(param.argLst); if (i + 1 < param.sig.numArgs) { strcat_s(retName, length, ","); } } } strcat_s(retName, length, ")"); if (param.returnType != nullptr) { strcat_s(retName, length, ":"); strcat_s(retName, length, param.returnType); } if (param.hasThis) { strcat_s(retName, length, ":this"); } assert(strlen(retName) == (length - 1)); return (retName); } #pragma warning(pop) #endif // defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) /*****************************************************************************/
-1
dotnet/runtime
66,227
Replace CngCommon hash with OneShotHashHelpers
The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
vcsjones
2022-03-05T00:49:31Z
2022-03-05T03:49:08Z
94480f128c8af3e728b2b6e5ad2b13370f97b8f1
eb57c1276add1ec7e35897bfdbbebb648839dee3
Replace CngCommon hash with OneShotHashHelpers. The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
./src/libraries/System.Private.Xml/tests/XmlReader/ReadContentAs/ReadAsTimeZoneInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Xml.Tests { public class TimeZoneInfoTests { [Fact] public static void ReadContentAsTimeZoneInfo1() { var reader = Utils.CreateFragmentReader("<a>2000-02-29T23:59:59+13:60</a>"); reader.PositionOnElement("a"); reader.Read(); Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(TimeZoneInfo), null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Xml.Tests { public class TimeZoneInfoTests { [Fact] public static void ReadContentAsTimeZoneInfo1() { var reader = Utils.CreateFragmentReader("<a>2000-02-29T23:59:59+13:60</a>"); reader.PositionOnElement("a"); reader.Read(); Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(TimeZoneInfo), null)); } } }
-1
dotnet/runtime
66,227
Replace CngCommon hash with OneShotHashHelpers
The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
vcsjones
2022-03-05T00:49:31Z
2022-03-05T03:49:08Z
94480f128c8af3e728b2b6e5ad2b13370f97b8f1
eb57c1276add1ec7e35897bfdbbebb648839dee3
Replace CngCommon hash with OneShotHashHelpers. The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/AlignRight.Int32.0.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 AlignRightInt320() { var test = new ImmBinaryOpTest__AlignRightInt320(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // 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__AlignRightInt320 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__AlignRightInt320 testClass) { var result = Avx2.AlignRight(_fld1, _fld2, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static ImmBinaryOpTest__AlignRightInt320() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public ImmBinaryOpTest__AlignRightInt320() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[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.AlignRight( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), 0 ); 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.AlignRight( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.AlignRight( _clsVar1, _clsVar2, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__AlignRightInt320(); var result = Avx2.AlignRight(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.AlignRight(_fld1, _fld2, 0); 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.AlignRight(test._fld1, test._fld2, 0); 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(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != right[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<Int32>(Vector256<Int32>.0, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AlignRightInt320() { var test = new ImmBinaryOpTest__AlignRightInt320(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // 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__AlignRightInt320 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__AlignRightInt320 testClass) { var result = Avx2.AlignRight(_fld1, _fld2, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static ImmBinaryOpTest__AlignRightInt320() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public ImmBinaryOpTest__AlignRightInt320() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[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.AlignRight( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), 0 ); 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.AlignRight( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.AlignRight( _clsVar1, _clsVar2, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__AlignRightInt320(); var result = Avx2.AlignRight(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.AlignRight(_fld1, _fld2, 0); 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.AlignRight(test._fld1, test._fld2, 0); 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(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != right[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<Int32>(Vector256<Int32>.0, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,227
Replace CngCommon hash with OneShotHashHelpers
The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
vcsjones
2022-03-05T00:49:31Z
2022-03-05T03:49:08Z
94480f128c8af3e728b2b6e5ad2b13370f97b8f1
eb57c1276add1ec7e35897bfdbbebb648839dee3
Replace CngCommon hash with OneShotHashHelpers. The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
./src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Serialization { using System; using System.IO; using System.Collections; using System.ComponentModel; using System.Threading; using System.Reflection; using System.Security; using System.Globalization; using System.Diagnostics.CodeAnalysis; ///<internalonly/> public abstract class XmlSerializationGeneratedCode { internal void Init(TempAssembly? tempAssembly) { } // this method must be called at the end of serialization internal void Dispose() { } } internal class XmlSerializationCodeGen { private readonly IndentedWriter _writer; private int _nextMethodNumber; private readonly Hashtable _methodNames = new Hashtable(); private readonly ReflectionAwareCodeGen _raCodeGen; private readonly TypeScope[] _scopes; private readonly TypeDesc? _stringTypeDesc; private readonly TypeDesc? _qnameTypeDesc; private readonly string _access; private readonly string _className; private TypeMapping[]? _referencedMethods; private int _references; private readonly Hashtable _generatedMethods = new Hashtable(); [RequiresUnreferencedCode("Calls GetTypeDesc")] internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) { _writer = writer; _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareCodeGen(writer); _className = className; _access = access; } internal IndentedWriter Writer { get { return _writer; } } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal string Access { get { return _access; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Hashtable MethodNames { get { return _methodNames; } } internal Hashtable GeneratedMethods { get { return _generatedMethods; } } [RequiresUnreferencedCode("calls WriteStructMethod")] internal virtual void GenerateMethod(TypeMapping mapping) { } [RequiresUnreferencedCode("calls GenerateMethod")] internal void GenerateReferencedMethods() { while (_references > 0) { TypeMapping mapping = _referencedMethods![--_references]; GenerateMethod(mapping); } } internal string? ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { _referencedMethods = EnsureArrayIndex(_referencedMethods!, _references); _referencedMethods[_references++] = mapping; } } return (string?)_methodNames[mapping]; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; TypeMapping[] b = new TypeMapping[a.Length + 32]; Array.Copy(a, b, index); return b; } internal void WriteQuotedCSharpString(string? value) { _raCodeGen.WriteQuotedCSharpString(value); } internal void GenerateHashtableGetBegin(string privateName, string publicName) { _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(privateName); _writer.WriteLine(" = null;"); _writer.Write("public override "); _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(publicName); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine("get {"); _writer.Indent++; _writer.Write("if ("); _writer.Write(privateName); _writer.WriteLine(" == null) {"); _writer.Indent++; _writer.Write(typeof(Hashtable).FullName); _writer.Write(" _tmp = new "); _writer.Write(typeof(Hashtable).FullName); _writer.WriteLine("();"); } internal void GenerateHashtableGetEnd(string privateName) { _writer.Write("if ("); _writer.Write(privateName); _writer.Write(" == null) "); _writer.Write(privateName); _writer.WriteLine(" = _tmp;"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("return "); _writer.Write(privateName); _writer.WriteLine(";"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); } internal void GeneratePublicMethods(string privateName, string publicName, string?[] methods, XmlMapping[] xmlMappings) { GenerateHashtableGetBegin(privateName, publicName); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; _writer.Write("_tmp["); WriteQuotedCSharpString(xmlMappings[i].Key); _writer.Write("] = "); WriteQuotedCSharpString(methods[i]); _writer.WriteLine(";"); } } GenerateHashtableGetEnd(privateName); } internal void GenerateSupportedTypes(Type?[] types) { _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanSerialize("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; Hashtable uniqueTypes = new Hashtable(); for (int i = 0; i < types.Length; i++) { Type? type = types[i]; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (uniqueTypes[type] != null) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; uniqueTypes[type] = type; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.WriteLine(")) return true;"); } _writer.WriteLine("return false;"); _writer.Indent--; _writer.WriteLine("}"); } internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); _writer.WriteLine(); _writer.Write("public abstract class "); _writer.Write(CodeIdentifier.GetCSharpName(baseSerializer)); _writer.Write(" : "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" CreateReader() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(readerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" CreateWriter() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(writerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); return baseSerializer; } internal string GenerateTypedSerializer(string? readMethod, string? writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping!.TypeDesc!.Name)); serializerName = classes.AddUnique($"{serializerName}Serializer", mapping); _writer.WriteLine(); _writer.Write("public sealed class "); _writer.Write(CodeIdentifier.GetCSharpName(serializerName)); _writer.Write(" : "); _writer.Write(baseSerializer); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine(); _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanDeserialize("); _writer.Write(typeof(XmlReader).FullName); _writer.WriteLine(" xmlReader) {"); _writer.Indent++; if (mapping.Accessor.Any) { _writer.WriteLine("return true;"); } else { _writer.Write("return xmlReader.IsStartElement("); WriteQuotedCSharpString(mapping.Accessor.Name); _writer.Write(", "); WriteQuotedCSharpString(mapping.Accessor.Namespace); _writer.WriteLine(");"); } _writer.Indent--; _writer.WriteLine("}"); if (writeMethod != null) { _writer.WriteLine(); _writer.Write("protected override void Serialize(object objectToSerialize, "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" writer) {"); _writer.Indent++; _writer.Write("(("); _writer.Write(writerClass); _writer.Write(")writer)."); _writer.Write(writeMethod); _writer.Write("("); if (mapping is XmlMembersMapping) { _writer.Write("(object[])"); } _writer.WriteLine("objectToSerialize);"); _writer.Indent--; _writer.WriteLine("}"); } if (readMethod != null) { _writer.WriteLine(); _writer.Write("protected override object Deserialize("); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" reader) {"); _writer.Indent++; _writer.Write("return (("); _writer.Write(readerClass); _writer.Write(")reader)."); _writer.Write(readMethod); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); } _writer.Indent--; _writer.WriteLine("}"); return serializerName; } private void GenerateTypedSerializers(Hashtable serializers) { string privateName = "typedSerializers"; GenerateHashtableGetBegin(privateName, "TypedSerializers"); foreach (string key in serializers.Keys) { _writer.Write("_tmp.Add("); WriteQuotedCSharpString(key); _writer.Write(", new "); _writer.Write((string?)serializers[key]); _writer.WriteLine("());"); } GenerateHashtableGetEnd("typedSerializers"); } //GenerateGetSerializer(serializers, xmlMappings); private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings) { _writer.Write("public override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.Write(" GetSerializer("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; for (int i = 0; i < xmlMappings.Length; i++) { if (xmlMappings[i] is XmlTypeMapping) { Type? type = xmlMappings[i].Accessor.Mapping!.TypeDesc!.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); _writer.Write((string?)serializers[xmlMappings[i].Key!]); _writer.WriteLine("();"); } } _writer.WriteLine("return null;"); _writer.Indent--; _writer.WriteLine("}"); } internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type?[] types, string readerType, string?[] readMethods, string writerType, string?[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializerImplementation).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.Write(" Reader { get { return new "); _writer.Write(readerType); _writer.WriteLine("(); } }"); _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.Write(" Writer { get { return new "); _writer.Write(writerType); _writer.WriteLine("(); } }"); GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings); GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings); GenerateTypedSerializers(serializers); GenerateSupportedTypes(types); GenerateGetSerializer(serializers, xmlMappings); _writer.Indent--; _writer.WriteLine("}"); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc!.CanBeElementValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Serialization { using System; using System.IO; using System.Collections; using System.ComponentModel; using System.Threading; using System.Reflection; using System.Security; using System.Globalization; using System.Diagnostics.CodeAnalysis; ///<internalonly/> public abstract class XmlSerializationGeneratedCode { internal void Init(TempAssembly? tempAssembly) { } // this method must be called at the end of serialization internal void Dispose() { } } internal class XmlSerializationCodeGen { private readonly IndentedWriter _writer; private int _nextMethodNumber; private readonly Hashtable _methodNames = new Hashtable(); private readonly ReflectionAwareCodeGen _raCodeGen; private readonly TypeScope[] _scopes; private readonly TypeDesc? _stringTypeDesc; private readonly TypeDesc? _qnameTypeDesc; private readonly string _access; private readonly string _className; private TypeMapping[]? _referencedMethods; private int _references; private readonly Hashtable _generatedMethods = new Hashtable(); [RequiresUnreferencedCode("Calls GetTypeDesc")] internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) { _writer = writer; _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareCodeGen(writer); _className = className; _access = access; } internal IndentedWriter Writer { get { return _writer; } } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal string Access { get { return _access; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Hashtable MethodNames { get { return _methodNames; } } internal Hashtable GeneratedMethods { get { return _generatedMethods; } } [RequiresUnreferencedCode("calls WriteStructMethod")] internal virtual void GenerateMethod(TypeMapping mapping) { } [RequiresUnreferencedCode("calls GenerateMethod")] internal void GenerateReferencedMethods() { while (_references > 0) { TypeMapping mapping = _referencedMethods![--_references]; GenerateMethod(mapping); } } internal string? ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { _referencedMethods = EnsureArrayIndex(_referencedMethods!, _references); _referencedMethods[_references++] = mapping; } } return (string?)_methodNames[mapping]; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; TypeMapping[] b = new TypeMapping[a.Length + 32]; Array.Copy(a, b, index); return b; } internal void WriteQuotedCSharpString(string? value) { _raCodeGen.WriteQuotedCSharpString(value); } internal void GenerateHashtableGetBegin(string privateName, string publicName) { _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(privateName); _writer.WriteLine(" = null;"); _writer.Write("public override "); _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(publicName); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine("get {"); _writer.Indent++; _writer.Write("if ("); _writer.Write(privateName); _writer.WriteLine(" == null) {"); _writer.Indent++; _writer.Write(typeof(Hashtable).FullName); _writer.Write(" _tmp = new "); _writer.Write(typeof(Hashtable).FullName); _writer.WriteLine("();"); } internal void GenerateHashtableGetEnd(string privateName) { _writer.Write("if ("); _writer.Write(privateName); _writer.Write(" == null) "); _writer.Write(privateName); _writer.WriteLine(" = _tmp;"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("return "); _writer.Write(privateName); _writer.WriteLine(";"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); } internal void GeneratePublicMethods(string privateName, string publicName, string?[] methods, XmlMapping[] xmlMappings) { GenerateHashtableGetBegin(privateName, publicName); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; _writer.Write("_tmp["); WriteQuotedCSharpString(xmlMappings[i].Key); _writer.Write("] = "); WriteQuotedCSharpString(methods[i]); _writer.WriteLine(";"); } } GenerateHashtableGetEnd(privateName); } internal void GenerateSupportedTypes(Type?[] types) { _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanSerialize("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; Hashtable uniqueTypes = new Hashtable(); for (int i = 0; i < types.Length; i++) { Type? type = types[i]; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (uniqueTypes[type] != null) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; uniqueTypes[type] = type; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.WriteLine(")) return true;"); } _writer.WriteLine("return false;"); _writer.Indent--; _writer.WriteLine("}"); } internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); _writer.WriteLine(); _writer.Write("public abstract class "); _writer.Write(CodeIdentifier.GetCSharpName(baseSerializer)); _writer.Write(" : "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" CreateReader() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(readerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" CreateWriter() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(writerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); return baseSerializer; } internal string GenerateTypedSerializer(string? readMethod, string? writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping!.TypeDesc!.Name)); serializerName = classes.AddUnique($"{serializerName}Serializer", mapping); _writer.WriteLine(); _writer.Write("public sealed class "); _writer.Write(CodeIdentifier.GetCSharpName(serializerName)); _writer.Write(" : "); _writer.Write(baseSerializer); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine(); _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanDeserialize("); _writer.Write(typeof(XmlReader).FullName); _writer.WriteLine(" xmlReader) {"); _writer.Indent++; if (mapping.Accessor.Any) { _writer.WriteLine("return true;"); } else { _writer.Write("return xmlReader.IsStartElement("); WriteQuotedCSharpString(mapping.Accessor.Name); _writer.Write(", "); WriteQuotedCSharpString(mapping.Accessor.Namespace); _writer.WriteLine(");"); } _writer.Indent--; _writer.WriteLine("}"); if (writeMethod != null) { _writer.WriteLine(); _writer.Write("protected override void Serialize(object objectToSerialize, "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" writer) {"); _writer.Indent++; _writer.Write("(("); _writer.Write(writerClass); _writer.Write(")writer)."); _writer.Write(writeMethod); _writer.Write("("); if (mapping is XmlMembersMapping) { _writer.Write("(object[])"); } _writer.WriteLine("objectToSerialize);"); _writer.Indent--; _writer.WriteLine("}"); } if (readMethod != null) { _writer.WriteLine(); _writer.Write("protected override object Deserialize("); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" reader) {"); _writer.Indent++; _writer.Write("return (("); _writer.Write(readerClass); _writer.Write(")reader)."); _writer.Write(readMethod); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); } _writer.Indent--; _writer.WriteLine("}"); return serializerName; } private void GenerateTypedSerializers(Hashtable serializers) { string privateName = "typedSerializers"; GenerateHashtableGetBegin(privateName, "TypedSerializers"); foreach (string key in serializers.Keys) { _writer.Write("_tmp.Add("); WriteQuotedCSharpString(key); _writer.Write(", new "); _writer.Write((string?)serializers[key]); _writer.WriteLine("());"); } GenerateHashtableGetEnd("typedSerializers"); } //GenerateGetSerializer(serializers, xmlMappings); private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings) { _writer.Write("public override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.Write(" GetSerializer("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; for (int i = 0; i < xmlMappings.Length; i++) { if (xmlMappings[i] is XmlTypeMapping) { Type? type = xmlMappings[i].Accessor.Mapping!.TypeDesc!.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); _writer.Write((string?)serializers[xmlMappings[i].Key!]); _writer.WriteLine("();"); } } _writer.WriteLine("return null;"); _writer.Indent--; _writer.WriteLine("}"); } internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type?[] types, string readerType, string?[] readMethods, string writerType, string?[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializerImplementation).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.Write(" Reader { get { return new "); _writer.Write(readerType); _writer.WriteLine("(); } }"); _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.Write(" Writer { get { return new "); _writer.Write(writerType); _writer.WriteLine("(); } }"); GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings); GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings); GenerateTypedSerializers(serializers); GenerateSupportedTypes(types); GenerateGetSerializer(serializers, xmlMappings); _writer.Indent--; _writer.WriteLine("}"); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc!.CanBeElementValue; } } }
-1
dotnet/runtime
66,227
Replace CngCommon hash with OneShotHashHelpers
The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
vcsjones
2022-03-05T00:49:31Z
2022-03-05T03:49:08Z
94480f128c8af3e728b2b6e5ad2b13370f97b8f1
eb57c1276add1ec7e35897bfdbbebb648839dee3
Replace CngCommon hash with OneShotHashHelpers. The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
./src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.C.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.Buffers.Text { public static partial class Utf8Parser { private static bool TryParseTimeSpanC(ReadOnlySpan<byte> source, out TimeSpan value, out int bytesConsumed) { TimeSpanSplitter s = default; if (!s.TrySplitTimeSpan(source, periodUsedToSeparateDay: true, out bytesConsumed)) { value = default; return false; } bool isNegative = s.IsNegative; bool success; switch (s.Separators) { case 0x00000000: // dd success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: 0, minutes: 0, seconds: 0, fraction: 0, out value); break; case 0x01000000: // hh:mm success = TryCreateTimeSpan(isNegative: isNegative, days: 0, hours: s.V1, minutes: s.V2, seconds: 0, fraction: 0, out value); break; case 0x02010000: // dd.hh:mm success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: s.V2, minutes: s.V3, seconds: 0, fraction: 0, out value); break; case 0x01010000: // hh:mm:ss success = TryCreateTimeSpan(isNegative: isNegative, days: 0, hours: s.V1, minutes: s.V2, seconds: s.V3, fraction: 0, out value); break; case 0x02010100: // dd.hh:mm:ss success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: s.V2, minutes: s.V3, seconds: s.V4, fraction: 0, out value); break; case 0x01010200: // hh:mm:ss.fffffff success = TryCreateTimeSpan(isNegative: isNegative, days: 0, hours: s.V1, minutes: s.V2, seconds: s.V3, fraction: s.V4, out value); break; case 0x02010102: // dd.hh:mm:ss.fffffff success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: s.V2, minutes: s.V3, seconds: s.V4, fraction: s.V5, out value); break; default: value = default; success = false; break; } if (!success) { bytesConsumed = 0; 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. namespace System.Buffers.Text { public static partial class Utf8Parser { private static bool TryParseTimeSpanC(ReadOnlySpan<byte> source, out TimeSpan value, out int bytesConsumed) { TimeSpanSplitter s = default; if (!s.TrySplitTimeSpan(source, periodUsedToSeparateDay: true, out bytesConsumed)) { value = default; return false; } bool isNegative = s.IsNegative; bool success; switch (s.Separators) { case 0x00000000: // dd success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: 0, minutes: 0, seconds: 0, fraction: 0, out value); break; case 0x01000000: // hh:mm success = TryCreateTimeSpan(isNegative: isNegative, days: 0, hours: s.V1, minutes: s.V2, seconds: 0, fraction: 0, out value); break; case 0x02010000: // dd.hh:mm success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: s.V2, minutes: s.V3, seconds: 0, fraction: 0, out value); break; case 0x01010000: // hh:mm:ss success = TryCreateTimeSpan(isNegative: isNegative, days: 0, hours: s.V1, minutes: s.V2, seconds: s.V3, fraction: 0, out value); break; case 0x02010100: // dd.hh:mm:ss success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: s.V2, minutes: s.V3, seconds: s.V4, fraction: 0, out value); break; case 0x01010200: // hh:mm:ss.fffffff success = TryCreateTimeSpan(isNegative: isNegative, days: 0, hours: s.V1, minutes: s.V2, seconds: s.V3, fraction: s.V4, out value); break; case 0x02010102: // dd.hh:mm:ss.fffffff success = TryCreateTimeSpan(isNegative: isNegative, days: s.V1, hours: s.V2, minutes: s.V3, seconds: s.V4, fraction: s.V5, out value); break; default: value = default; success = false; break; } if (!success) { bytesConsumed = 0; return false; } return true; } } }
-1
dotnet/runtime
66,227
Replace CngCommon hash with OneShotHashHelpers
The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
vcsjones
2022-03-05T00:49:31Z
2022-03-05T03:49:08Z
94480f128c8af3e728b2b6e5ad2b13370f97b8f1
eb57c1276add1ec7e35897bfdbbebb648839dee3
Replace CngCommon hash with OneShotHashHelpers. The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
./src/tests/JIT/jit64/regress/ddb/87766/ddb87766.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; public class VInline { private int _fi1; private int _fi2; public VInline(int ival) { _fi1 = ival; _fi2 = 0; } [MethodImpl(MethodImplOptions.NoInlining)] private void GetI1(ref int i) { i = _fi1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Accumulate(int a) { int i = 0; GetI1(ref i); //here's the ldloca, passing the address of i as the arg i = i / _fi2; //fi2 == 0 so this should always cause an exception return i; } } public class VIMain { public static int Main() { int ret = 100; VInline vi = new VInline(1); int ival = 2; try { ival = vi.Accumulate(ival); //this call should throw a divide by zero exception } catch (DivideByZeroException e) { Console.WriteLine("exeption stack trace: " + e.StackTrace.ToString()); //display the stack trace if (e.StackTrace.ToString().Contains("Accumulate")) { Console.WriteLine("Fail, method Accumulate NOT inlined."); ret = 666; } else { Console.WriteLine("Pass, method Accumulate inlined."); } } return ret; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; public class VInline { private int _fi1; private int _fi2; public VInline(int ival) { _fi1 = ival; _fi2 = 0; } [MethodImpl(MethodImplOptions.NoInlining)] private void GetI1(ref int i) { i = _fi1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Accumulate(int a) { int i = 0; GetI1(ref i); //here's the ldloca, passing the address of i as the arg i = i / _fi2; //fi2 == 0 so this should always cause an exception return i; } } public class VIMain { public static int Main() { int ret = 100; VInline vi = new VInline(1); int ival = 2; try { ival = vi.Accumulate(ival); //this call should throw a divide by zero exception } catch (DivideByZeroException e) { Console.WriteLine("exeption stack trace: " + e.StackTrace.ToString()); //display the stack trace if (e.StackTrace.ToString().Contains("Accumulate")) { Console.WriteLine("Fail, method Accumulate NOT inlined."); ret = 666; } else { Console.WriteLine("Pass, method Accumulate inlined."); } } return ret; } }
-1
dotnet/runtime
66,227
Replace CngCommon hash with OneShotHashHelpers
The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
vcsjones
2022-03-05T00:49:31Z
2022-03-05T03:49:08Z
94480f128c8af3e728b2b6e5ad2b13370f97b8f1
eb57c1276add1ec7e35897bfdbbebb648839dee3
Replace CngCommon hash with OneShotHashHelpers. The CNG asymmetric algorithms will benefit from the better one-shot implementations and reduce duplicate functionality.
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/ldind_u1.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ldind_u1.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ldind_u1.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./eng/testing/tests.wasm.targets
<Project> <!-- We need to set this in order to get extensibility on xunit category traits and other arguments we pass down to xunit via MSBuild properties --> <PropertyGroup> <IsWasmProject Condition="'$(IsWasmProject)' == ''">true</IsWasmProject> <WasmGenerateAppBundle Condition="'$(WasmGenerateAppBundle)' == ''">true</WasmGenerateAppBundle> <BundleTestAppTargets>$(BundleTestAppTargets);BundleTestWasmApp</BundleTestAppTargets> <DebuggerSupport Condition="'$(DebuggerSupport)' == '' and '$(Configuration)' == 'Debug'">true</DebuggerSupport> <!-- set this when provisioning emsdk on CI --> <EMSDK_PATH Condition="'$(EMSDK_PATH)' == '' and '$(ContinuousIntegrationBuild)' == 'true' and '$(MonoProjectRoot)' != ''">$([MSBuild]::NormalizeDirectory($(MonoProjectRoot), 'wasm', 'emsdk'))</EMSDK_PATH> <!-- Some tests expect to load satellite assemblies by path, eg. System.Runtime.Loader.Tests, so, just setting it true by default --> <IncludeSatelliteAssembliesInVFS Condition="'$(IncludeSatelliteAssembliesInVFS)' == ''">true</IncludeSatelliteAssembliesInVFS> <!-- - For regular library tests, it will use the symbols file from the runtime pack. - for AOT library tests, we use WasmNativeStrip=false, so we already have symbols --> <WasmNativeStrip Condition="'$(WasmNativeStrip)' == ''">false</WasmNativeStrip> <WasmEmitSymbolMap Condition="'$(WasmEmitSymbolMap)' == '' and '$(RunAOTCompilation)' != 'true'">true</WasmEmitSymbolMap> <!-- Run only if previous command succeeded --> <_ShellCommandSeparator Condition="'$(OS)' == 'Windows_NT'">&amp;&amp;</_ShellCommandSeparator> <_ShellCommandSeparator Condition="'$(OS)' != 'Windows_NT'">&amp;&amp;</_ShellCommandSeparator> <_WasmMainJSFileName Condition="'$(WasmMainJSPath)' != ''">$([System.IO.Path]::GetFileName('$(WasmMainJSPath)'))</_WasmMainJSFileName> <_WasmStrictVersionMatch Condition="'$(ContinuousIntegrationBuild)' == 'true'">true</_WasmStrictVersionMatch> <XUnitUseRandomizedTestOrderer Condition="'$(XUnitUseRandomizedTestOrderer)' == '' and '$(IsTestProject)' == 'true'">true</XUnitUseRandomizedTestOrderer> </PropertyGroup> <PropertyGroup> <BuildAOTTestsOn Condition="'$(ContinuousIntegrationBuild)' == 'true' and '$(Scenario)' == 'BuildWasmApps'">helix</BuildAOTTestsOn> <BuildAOTTestsOn Condition="'$(BuildAOTTestsOnHelix)' == 'true'">helix</BuildAOTTestsOn> <BuildAOTTestsOn Condition="'$(BuildAOTTestsOn)' == ''">local</BuildAOTTestsOn> </PropertyGroup> <ItemGroup> <_AOT_InternalForceInterpretAssemblies Include="@(HighAotMemoryUsageAssembly)" /> </ItemGroup> <!-- This is running during compile time and therefore $(Scenario) is empty, unless the specific project sets it. Any settings in the project file could be replaced on Helix. See also eng\testing\WasmRunnerTemplate.sh --> <ItemGroup Condition="'$(OS)' != 'Windows_NT'"> <SetScriptCommands Condition="'$(Scenario)' != '' and '$(ContinuousIntegrationBuild)' != 'true'" Include="export SCENARIO=$(Scenario)" /> <SetScriptCommands Condition="'$(JSEngine)' != ''" Include="export JS_ENGINE=--engine=$(JSEngine)" /> <SetScriptCommands Condition="'$(JSEngineArgs)' != ''" Include="export JS_ENGINE_ARGS=$(JSEngineArgs)" /> <SetScriptCommands Condition="'$(_WasmMainJSFileName)' != ''" Include="export MAIN_JS=--js-file=$(_WasmMainJSFileName)" /> </ItemGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> <SetScriptCommands Condition="'$(Scenario)' != '' and '$(ContinuousIntegrationBuild)' != 'true'" Include="set &quot;SCENARIO=$(Scenario)&quot;" /> <SetScriptCommands Condition="'$(JSEngine)' != ''" Include="set &quot;JS_ENGINE=--engine^=$(JSEngine)&quot;" /> <SetScriptCommands Condition="'$(JSEngineArgs)' != ''" Include="set &quot;JS_ENGINE_ARGS=$(JSEngineArgs)&quot;" /> <SetScriptCommands Condition="'$(_WasmMainJSFileName)' != ''" Include="set &quot;MAIN_JS=--js-file^=$(_WasmMainJSFileName)&quot;" /> </ItemGroup> <PropertyGroup> <_AppArgs Condition="'$(IsFunctionalTest)' != 'true' and '$(Scenario)' != 'BuildWasmApps' and '$(WasmMainAssemblyFileName)' == ''">--run WasmTestRunner.dll $(AssemblyName).dll</_AppArgs> <_AppArgs Condition="'$(IsFunctionalTest)' != 'true' and '$(WasmMainAssemblyFileName)' != ''">--run $(WasmMainAssemblyFileName)</_AppArgs> <_AppArgs Condition="'$(IsFunctionalTest)' == 'true'">--run $(AssemblyName).dll</_AppArgs> <_AppArgs Condition="'$(WasmTestAppArgs)' != ''">$(_AppArgs) $(WasmTestAppArgs)</_AppArgs> <WasmXHarnessMonoArgs Condition="'$(XunitShowProgress)' == 'true'">$(WasmXHarnessMonoArgs) --setenv=XHARNESS_LOG_TEST_START=1</WasmXHarnessMonoArgs> </PropertyGroup> <PropertyGroup Condition="'$(RunScriptCommand)' == ''"> <_XHarnessArgs Condition="'$(OS)' != 'Windows_NT'">wasm $XHARNESS_COMMAND --app=. --output-directory=$XHARNESS_OUT</_XHarnessArgs> <_XHarnessArgs Condition="'$(OS)' == 'Windows_NT'">wasm %XHARNESS_COMMAND% --app=. --output-directory=%XHARNESS_OUT%</_XHarnessArgs> <_XHarnessArgs Condition="'$(IsFunctionalTest)' == 'true'" >$(_XHarnessArgs) --expected-exit-code=$(ExpectedExitCode)</_XHarnessArgs> <_XHarnessArgs Condition="'$(WasmXHarnessArgs)' != ''" >$(_XHarnessArgs) $(WasmXHarnessArgs)</_XHarnessArgs> <_XHarnessArgs >$(_XHarnessArgs) -s dotnet.js.symbols</_XHarnessArgs> <_XHarnessArgs Condition="'$(WasmXHarnessArgsCli)' != ''" >$(_XHarnessArgs) $(WasmXHarnessArgsCli)</_XHarnessArgs> <!-- There two flavors of WasmXHarnessArgs and WasmXHarnessMonoArgs, one is MSBuild property and the other is environment variable --> <RunScriptCommand Condition="'$(OS)' != 'Windows_NT'">$HARNESS_RUNNER $(_XHarnessArgs) %24XHARNESS_ARGS %24WasmXHarnessArgs -- $(WasmXHarnessMonoArgs) %24WasmXHarnessMonoArgs $(_AppArgs) %24WasmTestAppArgs</RunScriptCommand> <RunScriptCommand Condition="'$(OS)' == 'Windows_NT'">%HARNESS_RUNNER% $(_XHarnessArgs) %XHARNESS_ARGS% %WasmXHarnessArgs% -- $(WasmXHarnessMonoArgs) %WasmXHarnessMonoArgs% $(_AppArgs) %WasmTestAppArgs%</RunScriptCommand> </PropertyGroup> <PropertyGroup Condition="'$(BuildAOTTestsOnHelix)' == 'true'"> <_AOTBuildCommand Condition="'$(BrowserHost)' != 'windows'">_buildAOTFunc publish/ProxyProjectForAOTOnHelix.proj $XHARNESS_OUT/AOTBuild.binlog</_AOTBuildCommand> <_AOTBuildCommand Condition="'$(BrowserHost)' == 'windows'">dotnet msbuild publish/ProxyProjectForAOTOnHelix.proj /bl:%XHARNESS_OUT%/AOTBuild.binlog</_AOTBuildCommand> <_AOTBuildCommand Condition="'$(BrowserHost)' == 'windows'">$(_AOTBuildCommand) &quot;/p:WasmCachePath=%USERPROFILE%\.emscripten-cache&quot;</_AOTBuildCommand> <!-- running aot-helix tests locally, so we can test with the same project file as CI --> <_AOTBuildCommand Condition="'$(ContinuousIntegrationBuild)' != 'true'">$(_AOTBuildCommand) /p:RuntimeSrcDir=$(RepoRoot) /p:RuntimeConfig=$(Configuration)</_AOTBuildCommand> <_AOTBuildCommand>$(_AOTBuildCommand) /p:RunAOTCompilation=$(RunAOTCompilation)</_AOTBuildCommand> <_AOTBuildCommand>$(_AOTBuildCommand) $(_ShellCommandSeparator) cd wasm_build/AppBundle</_AOTBuildCommand> <RunScriptCommand Condition="'$(RunScriptCommand)' == ''">$(_AOTBuildCommand)</RunScriptCommand> <RunScriptCommand Condition="'$(RunScriptCommand)' != ''">$(_AOTBuildCommand) $(_ShellCommandSeparator) $(RunScriptCommand)</RunScriptCommand> </PropertyGroup> <!-- Don't include InTree.props here, because the test projects themselves can set the target* properties --> <Import Project="$(MonoProjectRoot)\wasm\build\WasmApp.props" Condition="'$(BuildAOTTestsOn)' == 'local'" /> <Import Project="$(MonoProjectRoot)\wasm\build\WasmApp.InTree.targets" Condition="'$(BuildAOTTestsOn)' == 'local'" /> <PropertyGroup> <BundleTestWasmAppDependsOn Condition="'$(BuildAOTTestsOn)' == 'local'">WasmTriggerPublishApp</BundleTestWasmAppDependsOn> <BundleTestWasmAppDependsOn Condition="'$(BuildAOTTestsOnHelix)' == 'true'">$(BundleTestWasmAppDependsOn);_BundleAOTTestWasmAppForHelix</BundleTestWasmAppDependsOn> <RunCommand>$(WasmAppHostDir)/WasmAppHost</RunCommand> <!-- Use BundleDir here, since WasmAppDir is set in a target, and `dotnet run` reads $(Run*) without running any targets --> <RunArguments>--runtime-config $(BundleDir)/WasmTestRunner.runtimeconfig.json $(WasmHostArguments) $(StartArguments) $(WasmXHarnessMonoArgs) $(_AppArgs)</RunArguments> </PropertyGroup> <PropertyGroup Condition="'$(BuildAOTTestsOnHelix)' == 'true'"> <!-- wasm targets are not imported at all, in this case, because we run the wasm build on helix --> </PropertyGroup> <PropertyGroup Condition="'$(BuildAOTTestsOnHelix)' != 'true'"> <WasmBuildOnlyAfterPublish>true</WasmBuildOnlyAfterPublish> <!-- wasm's publish targets will trigger publish, so we shouldn't do that --> <PublishTestAsSelfContainedDependsOn /> <WasmNestedPublishAppDependsOn>PrepareForWasmBuildApp;$(WasmNestedPublishAppDependsOn)</WasmNestedPublishAppDependsOn> </PropertyGroup> <ItemGroup> <WorkloadIdForTesting Include="wasm-tools" ManifestName="Microsoft.NET.Workload.Mono.ToolChain" Version="$(PackageVersion)" VersionBand="$(SdkBandVersion)" /> </ItemGroup> <Target Name="BundleTestWasmApp" DependsOnTargets="$(BundleTestWasmAppDependsOn)" /> <UsingTask Condition="'$(BuildAOTTestsOnHelix)' == 'true'" TaskName="Microsoft.WebAssembly.Build.Tasks.GenerateAOTProps" AssemblyFile="$(WasmBuildTasksAssemblyPath)" /> <Target Name="_BundleAOTTestWasmAppForHelix" DependsOnTargets="PrepareForWasmBuildApp"> <PropertyGroup Condition="'$(IsHighAotMemoryUsageTest)' == 'true' and '$(ContinuousIntegrationBuild)' == 'true'"> <DisableParallelEmccCompile Condition="'$(DisableParallelEmccCompile)' == ''">true</DisableParallelEmccCompile> <EmccLinkOptimizationFlag Condition="'$(EmccLinkOptimizationFlag)' == ''">-O2</EmccLinkOptimizationFlag> </PropertyGroup> <PropertyGroup> <_MainAssemblyPath Condition="'%(WasmAssembliesToBundle.FileName)' == $(AssemblyName) and '%(WasmAssembliesToBundle.Extension)' == '.dll'">%(WasmAssembliesToBundle.Identity)</_MainAssemblyPath> <RuntimeConfigFilePath>$([System.IO.Path]::ChangeExtension($(_MainAssemblyPath), '.runtimeconfig.json'))</RuntimeConfigFilePath> <EmccLinkOptimizationFlag Condition="'$(EmccLinkOptimizationFlag)' == ''">-Oz -Wl,-O0 -Wl,-lto-O0</EmccLinkOptimizationFlag> </PropertyGroup> <Error Text="Item WasmAssembliesToBundle is empty. This is likely an authoring error." Condition="@(WasmAssembliesToBundle->Count()) == 0" /> <ItemGroup> <BundleFiles Include="$(WasmMainJSPath)" TargetDir="publish" /> <BundleFiles Include="@(WasmAssembliesToBundle)" TargetDir="publish\%(WasmAssembliesToBundle.RecursiveDir)" /> <BundleFiles Include="$(RuntimeConfigFilePath)" TargetDir="publish" /> <BundleFiles Include="$(MonoProjectRoot)\wasm\data\aot-tests\*" TargetDir="publish" /> </ItemGroup> <ItemGroup Condition="'$(DebuggerSupport)' == 'true'"> <!-- Add any pdb files, if available --> <_BundlePdbFiles Include="$([System.IO.Path]::ChangeExtension('%(WasmAssembliesToBundle.Identity)', '.pdb'))" /> <BundleFiles Include="@(_BundlePdbFiles)" TargetDir="publish" Condition="Exists(%(_BundlePdbFiles.Identity))" /> </ItemGroup> <!-- To recreate the original project on helix, we need to set the wasm properties also, same as the library test project. Eg. $(InvariantGlobalization) --> <ItemGroup> <_WasmPropertyNames Include="AOTMode" /> <_WasmPropertyNames Include="AssemblyName" /> <_WasmPropertyNames Include="DisableParallelAot" /> <_WasmPropertyNames Include="DisableParallelEmccCompile" /> <_WasmPropertyNames Include="EmccCompileOptimizationFlag" /> <_WasmPropertyNames Include="EmccLinkOptimizationFlag" /> <_WasmPropertyNames Include="IncludeSatelliteAssembliesInVFS" /> <_WasmPropertyNames Include="InvariantGlobalization" /> <_WasmPropertyNames Include="WasmBuildNative" /> <_WasmPropertyNames Include="WasmDebugLevel" /> <_WasmPropertyNames Include="WasmDedup" /> <_WasmPropertyNames Include="WasmLinkIcalls" /> <_WasmPropertyNames Include="WasmNativeStrip" /> <_WasmPropertyNames Include="WasmEnableES6" /> <_WasmPropertyNames Include="_WasmDevel" /> <_WasmPropertyNames Include="_WasmStrictVersionMatch" /> <_WasmPropertyNames Include="WasmEmitSymbolMap" /> <_WasmPropertiesToPass Include="$(%(_WasmPropertyNames.Identity))" Name="%(_WasmPropertyNames.Identity)" ConditionToUse__="%(_WasmPropertyNames.ConditionToUse__)" /> <_WasmVFSFilesToCopy Include="@(WasmFilesToIncludeInFileSystem)" /> <_WasmVFSFilesToCopy TargetPath="%(FileName)%(Extension)" Condition="'%(_WasmVFSFilesToCopy.TargetPath)' == ''" /> <_WasmExtraFilesToCopy Include="@(WasmExtraFilesToDeploy)" /> <_WasmExtraFilesToCopy TargetPath="%(FileName)%(Extension)" Condition="'%(_WasmExtraFilesToCopy.TargetPath)' == ''" /> <!-- Example of passing items to the project <_WasmItemsToPass Include="@(BundleFiles)" OriginalItemName__="BundleFiles" ConditionToUse__="'$(Foo)' != 'true'" /> --> <_WasmItemsToPass Include="@(_AOT_InternalForceInterpretAssemblies)" OriginalItemName__="_AOT_InternalForceInterpretAssemblies" /> </ItemGroup> <!-- This file gets imported by the project file on helix --> <GenerateAOTProps Properties="@(_WasmPropertiesToPass)" Items="@(_WasmItemsToPass)" OutputFile="$(BundleDir)publish\ProxyProjectForAOTOnHelix.props" /> <Copy SourceFiles="@(BundleFiles)" DestinationFolder="$(BundleDir)%(TargetDir)" /> <Copy SourceFiles="@(_WasmVFSFilesToCopy)" DestinationFiles="$(BundleDir)\vfsFiles\%(_WasmVFSFilesToCopy.TargetPath)" /> <Copy SourceFiles="@(_WasmExtraFilesToCopy)" DestinationFiles="$(BundleDir)\extraFiles\%(_WasmExtraFilesToCopy.TargetPath)" /> </Target> <Target Name="PrepareForWasmBuildApp"> <PropertyGroup> <WasmAppDir>$(BundleDir)</WasmAppDir> <WasmMainAssemblyFileName Condition="'$(WasmMainAssemblyFileName)' == ''">WasmTestRunner.dll</WasmMainAssemblyFileName> <WasmMainJSPath Condition="'$(WasmMainJSPath)' == ''">$(MonoProjectRoot)\wasm\test-main.js</WasmMainJSPath> <WasmInvariantGlobalization>$(InvariantGlobalization)</WasmInvariantGlobalization> <WasmGenerateRunV8Script>true</WasmGenerateRunV8Script> <WasmNativeDebugSymbols Condition="'$(DebuggerSupport)' == 'true' and '$(WasmNativeDebugSymbols)' == ''">true</WasmNativeDebugSymbols> <WasmDebugLevel Condition="'$(DebuggerSupport)' == 'true' and '$(WasmDebugLevel)' == ''">-1</WasmDebugLevel> </PropertyGroup> <ItemGroup Condition="'$(IncludeSatelliteAssembliesInVFS)' == 'true' and '$(BuildAOTTestsOnHelix)' != 'true'"> <_SatelliteAssemblies Include="$(PublishDir)*\*.resources.dll" /> <_SatelliteAssemblies CultureName="$([System.IO.Directory]::GetParent('%(Identity)').Name)" /> <_SatelliteAssemblies TargetPath="%(CultureName)\%(FileName)%(Extension)" /> <WasmFilesToIncludeInFileSystem Include="@(_SatelliteAssemblies)" /> </ItemGroup> <ItemGroup> <WasmAssembliesToBundle Include="$(PublishDir)\**\*.dll" Condition="'$(BuildAOTTestsOnHelix)' == 'true'" /> <WasmFilesToIncludeInFileSystem Include="@(ContentWithTargetPath)" /> <_CopyLocalPaths Include="@(PublishItemsOutputGroupOutputs)" Condition="'%(PublishItemsOutputGroupOutputs.BuildReference)' == 'true' and !$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.resources.dll'))" /> <_CopyLocalPaths TargetPath="%(_CopyLocalPaths.RelativePath)" Condition="'%(_CopyLocalPaths.RelativePath)' != ''" /> <_CopyLocalPaths TargetPath="%(FileName)%(Extension)" Condition="'%(_CopyLocalPaths.RelativePath)' == ''" /> <WasmFilesToIncludeInFileSystem Include="@(_CopyLocalPaths)" /> <!-- Include files specified by test projects from publish dir --> <WasmFilesToIncludeInFileSystem Include="$(PublishDir)%(WasmFilesToIncludeFromPublishDir.Identity)" TargetPath="%(WasmFilesToIncludeFromPublishDir.Identity)" Condition="'%(WasmFilesToIncludeFromPublishDir.Identity)' != ''" /> </ItemGroup> </Target> <!-- linker automatically picks up the .pdb files, but they are not added to the publish list. Add them explicitly here, so they can be used with WasmAppBuilder --> <Target Name="AddPdbFilesToPublishList" AfterTargets="ILLink" Condition="'$(DebuggerSupport)' == 'true'"> <ItemGroup> <_PdbFilesToCheck Include="$([System.IO.Path]::ChangeExtension('%(ResolvedFileToPublish.Identity)', '.pdb'))" Condition="'%(ResolvedFileToPublish.Extension)' == '.dll'" /> <ResolvedFileToPublish Include="@(_PdbFilesToCheck)" Condition="Exists(%(_PdbFilesToCheck.Identity))" RelativePath="%(_PdbFilesToCheck.FileName)%(_PdbFilesToCheck.Extension)" /> </ItemGroup> </Target> <Target Name="ProvideNodeNpmRestoreScripts" BeforeTargets="GenerateRunScript"> <!-- Combine optional alias on all NodeNpmModule and trim separator where alias is empty --> <ItemGroup> <_NodeNpmModuleString Include="%(NodeNpmModule.Identity):%(NodeNpmModule.Alias)" /> <_NodeNpmModuleStringTrimmed Include="@(_NodeNpmModuleString->Trim(':'))" /> </ItemGroup> <PropertyGroup> <NodeNpmModuleString>@(_NodeNpmModuleStringTrimmed, ',')</NodeNpmModuleString> </PropertyGroup> <!-- Restore NPM packages --> <ItemGroup Condition="'$(OS)' != 'Windows_NT'"> <SetScriptCommands Include="if [[ &quot;$SCENARIO&quot; == &quot;WasmTestOnNodeJs&quot; || &quot;$SCENARIO&quot; == &quot;wasmtestonnodejs&quot; ]]; then export WasmXHarnessMonoArgs=&quot;$WasmXHarnessMonoArgs --setenv=NPM_MODULES=$(NodeNpmModuleString)&quot;; fi" /> <RunScriptCommands Include="if [[ &quot;$SCENARIO&quot; == &quot;WasmTestOnNodeJs&quot; || &quot;$SCENARIO&quot; == &quot;wasmtestonnodejs&quot; ]]; then npm ci; fi" /> </ItemGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> <SetScriptCommands Include="if /I [%SCENARIO%]==[WasmTestOnNodeJS] ( set &quot;WasmXHarnessMonoArgs=%WasmXHarnessMonoArgs% --setenv=NPM_MODULES^=$(NodeNpmModuleString)&quot; )" /> <RunScriptCommands Include="if /I [%SCENARIO%]==[WasmTestOnNodeJS] ( call npm ci )" /> </ItemGroup> </Target> </Project>
<Project> <!-- We need to set this in order to get extensibility on xunit category traits and other arguments we pass down to xunit via MSBuild properties --> <PropertyGroup> <IsWasmProject Condition="'$(IsWasmProject)' == ''">true</IsWasmProject> <WasmGenerateAppBundle Condition="'$(WasmGenerateAppBundle)' == ''">true</WasmGenerateAppBundle> <BundleTestAppTargets>$(BundleTestAppTargets);BundleTestWasmApp</BundleTestAppTargets> <DebuggerSupport Condition="'$(DebuggerSupport)' == '' and '$(Configuration)' == 'Debug'">true</DebuggerSupport> <!-- set this when provisioning emsdk on CI --> <EMSDK_PATH Condition="'$(EMSDK_PATH)' == '' and '$(ContinuousIntegrationBuild)' == 'true' and '$(MonoProjectRoot)' != ''">$([MSBuild]::NormalizeDirectory($(MonoProjectRoot), 'wasm', 'emsdk'))</EMSDK_PATH> <!-- Some tests expect to load satellite assemblies by path, eg. System.Runtime.Loader.Tests, so, just setting it true by default --> <IncludeSatelliteAssembliesInVFS Condition="'$(IncludeSatelliteAssembliesInVFS)' == ''">true</IncludeSatelliteAssembliesInVFS> <!-- - For regular library tests, it will use the symbols file from the runtime pack. - for AOT library tests, we use WasmNativeStrip=false, so we already have symbols --> <WasmNativeStrip Condition="'$(WasmNativeStrip)' == ''">false</WasmNativeStrip> <WasmEmitSymbolMap Condition="'$(WasmEmitSymbolMap)' == '' and '$(RunAOTCompilation)' != 'true'">true</WasmEmitSymbolMap> <!-- Run only if previous command succeeded --> <_ShellCommandSeparator Condition="'$(OS)' == 'Windows_NT'">&amp;&amp;</_ShellCommandSeparator> <_ShellCommandSeparator Condition="'$(OS)' != 'Windows_NT'">&amp;&amp;</_ShellCommandSeparator> <_WasmMainJSFileName Condition="'$(WasmMainJSPath)' != ''">$([System.IO.Path]::GetFileName('$(WasmMainJSPath)'))</_WasmMainJSFileName> <_WasmStrictVersionMatch Condition="'$(ContinuousIntegrationBuild)' == 'true'">true</_WasmStrictVersionMatch> <XUnitUseRandomizedTestOrderer Condition="'$(XUnitUseRandomizedTestOrderer)' == '' and '$(IsTestProject)' == 'true'">true</XUnitUseRandomizedTestOrderer> <_UseWasmSymbolicator Condition="'$(TestTrimming)' != 'true'">true</_UseWasmSymbolicator> </PropertyGroup> <PropertyGroup> <BuildAOTTestsOn Condition="'$(ContinuousIntegrationBuild)' == 'true' and '$(Scenario)' == 'BuildWasmApps'">helix</BuildAOTTestsOn> <BuildAOTTestsOn Condition="'$(BuildAOTTestsOnHelix)' == 'true'">helix</BuildAOTTestsOn> <BuildAOTTestsOn Condition="'$(BuildAOTTestsOn)' == ''">local</BuildAOTTestsOn> </PropertyGroup> <ItemGroup> <_AOT_InternalForceInterpretAssemblies Include="@(HighAotMemoryUsageAssembly)" /> </ItemGroup> <!-- This is running during compile time and therefore $(Scenario) is empty, unless the specific project sets it. Any settings in the project file could be replaced on Helix. See also eng\testing\WasmRunnerTemplate.sh --> <ItemGroup Condition="'$(OS)' != 'Windows_NT'"> <SetScriptCommands Condition="'$(Scenario)' != '' and '$(ContinuousIntegrationBuild)' != 'true'" Include="export SCENARIO=$(Scenario)" /> <SetScriptCommands Condition="'$(JSEngine)' != ''" Include="export JS_ENGINE=--engine=$(JSEngine)" /> <SetScriptCommands Condition="'$(JSEngineArgs)' != ''" Include="export JS_ENGINE_ARGS=$(JSEngineArgs)" /> <SetScriptCommands Condition="'$(_WasmMainJSFileName)' != ''" Include="export MAIN_JS=--js-file=$(_WasmMainJSFileName)" /> </ItemGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> <SetScriptCommands Condition="'$(Scenario)' != '' and '$(ContinuousIntegrationBuild)' != 'true'" Include="set &quot;SCENARIO=$(Scenario)&quot;" /> <SetScriptCommands Condition="'$(JSEngine)' != ''" Include="set &quot;JS_ENGINE=--engine^=$(JSEngine)&quot;" /> <SetScriptCommands Condition="'$(JSEngineArgs)' != ''" Include="set &quot;JS_ENGINE_ARGS=$(JSEngineArgs)&quot;" /> <SetScriptCommands Condition="'$(_WasmMainJSFileName)' != ''" Include="set &quot;MAIN_JS=--js-file^=$(_WasmMainJSFileName)&quot;" /> </ItemGroup> <PropertyGroup> <_AppArgs Condition="'$(IsFunctionalTest)' != 'true' and '$(Scenario)' != 'BuildWasmApps' and '$(WasmMainAssemblyFileName)' == ''">--run WasmTestRunner.dll $(AssemblyName).dll</_AppArgs> <_AppArgs Condition="'$(IsFunctionalTest)' != 'true' and '$(WasmMainAssemblyFileName)' != ''">--run $(WasmMainAssemblyFileName)</_AppArgs> <_AppArgs Condition="'$(IsFunctionalTest)' == 'true'">--run $(AssemblyName).dll</_AppArgs> <_AppArgs Condition="'$(WasmTestAppArgs)' != ''">$(_AppArgs) $(WasmTestAppArgs)</_AppArgs> <WasmXHarnessMonoArgs Condition="'$(XunitShowProgress)' == 'true'">$(WasmXHarnessMonoArgs) --setenv=XHARNESS_LOG_TEST_START=1</WasmXHarnessMonoArgs> </PropertyGroup> <PropertyGroup Condition="'$(RunScriptCommand)' == ''"> <_XHarnessArgs Condition="'$(OS)' != 'Windows_NT'">wasm $XHARNESS_COMMAND --app=. --output-directory=$XHARNESS_OUT</_XHarnessArgs> <_XHarnessArgs Condition="'$(OS)' == 'Windows_NT'">wasm %XHARNESS_COMMAND% --app=. --output-directory=%XHARNESS_OUT%</_XHarnessArgs> <_XHarnessArgs Condition="'$(IsFunctionalTest)' == 'true'" >$(_XHarnessArgs) --expected-exit-code=$(ExpectedExitCode)</_XHarnessArgs> <_XHarnessArgs Condition="'$(WasmXHarnessArgs)' != ''" >$(_XHarnessArgs) $(WasmXHarnessArgs)</_XHarnessArgs> <_XHarnessArgs >$(_XHarnessArgs) -s dotnet.js.symbols</_XHarnessArgs> <_XHarnessArgs Condition="'$(_UseWasmSymbolicator)' == 'true'" >$(_XHarnessArgs) --symbol-patterns wasm-symbol-patterns.txt</_XHarnessArgs> <_XHarnessArgs Condition="'$(_UseWasmSymbolicator)' == 'true'" >$(_XHarnessArgs) --symbolicator WasmSymbolicator.dll,Microsoft.WebAssembly.Internal.SymbolicatorWrapperForXHarness</_XHarnessArgs> <_XHarnessArgs Condition="'$(WasmXHarnessArgsCli)' != ''" >$(_XHarnessArgs) $(WasmXHarnessArgsCli)</_XHarnessArgs> <!-- There two flavors of WasmXHarnessArgs and WasmXHarnessMonoArgs, one is MSBuild property and the other is environment variable --> <RunScriptCommand Condition="'$(OS)' != 'Windows_NT'">$HARNESS_RUNNER $(_XHarnessArgs) %24XHARNESS_ARGS %24WasmXHarnessArgs -- $(WasmXHarnessMonoArgs) %24WasmXHarnessMonoArgs $(_AppArgs) %24WasmTestAppArgs</RunScriptCommand> <RunScriptCommand Condition="'$(OS)' == 'Windows_NT'">%HARNESS_RUNNER% $(_XHarnessArgs) %XHARNESS_ARGS% %WasmXHarnessArgs% -- $(WasmXHarnessMonoArgs) %WasmXHarnessMonoArgs% $(_AppArgs) %WasmTestAppArgs%</RunScriptCommand> </PropertyGroup> <PropertyGroup Condition="'$(BuildAOTTestsOnHelix)' == 'true'"> <_AOTBuildCommand Condition="'$(BrowserHost)' != 'windows'">_buildAOTFunc publish/ProxyProjectForAOTOnHelix.proj $XHARNESS_OUT/AOTBuild.binlog</_AOTBuildCommand> <_AOTBuildCommand Condition="'$(BrowserHost)' == 'windows'">dotnet msbuild publish/ProxyProjectForAOTOnHelix.proj /bl:%XHARNESS_OUT%/AOTBuild.binlog</_AOTBuildCommand> <_AOTBuildCommand Condition="'$(BrowserHost)' == 'windows'">$(_AOTBuildCommand) &quot;/p:WasmCachePath=%USERPROFILE%\.emscripten-cache&quot;</_AOTBuildCommand> <!-- running aot-helix tests locally, so we can test with the same project file as CI --> <_AOTBuildCommand Condition="'$(ContinuousIntegrationBuild)' != 'true'">$(_AOTBuildCommand) /p:RuntimeSrcDir=$(RepoRoot) /p:RuntimeConfig=$(Configuration)</_AOTBuildCommand> <_AOTBuildCommand>$(_AOTBuildCommand) /p:RunAOTCompilation=$(RunAOTCompilation)</_AOTBuildCommand> <_AOTBuildCommand>$(_AOTBuildCommand) $(_ShellCommandSeparator) cd wasm_build/AppBundle</_AOTBuildCommand> <RunScriptCommand Condition="'$(RunScriptCommand)' == ''">$(_AOTBuildCommand)</RunScriptCommand> <RunScriptCommand Condition="'$(RunScriptCommand)' != ''">$(_AOTBuildCommand) $(_ShellCommandSeparator) $(RunScriptCommand)</RunScriptCommand> </PropertyGroup> <!-- Don't include InTree.props here, because the test projects themselves can set the target* properties --> <Import Project="$(MonoProjectRoot)\wasm\build\WasmApp.props" Condition="'$(BuildAOTTestsOn)' == 'local'" /> <Import Project="$(MonoProjectRoot)\wasm\build\WasmApp.InTree.targets" Condition="'$(BuildAOTTestsOn)' == 'local'" /> <PropertyGroup> <BundleTestWasmAppDependsOn Condition="'$(BuildAOTTestsOn)' == 'local'">WasmTriggerPublishApp</BundleTestWasmAppDependsOn> <BundleTestWasmAppDependsOn Condition="'$(BuildAOTTestsOnHelix)' == 'true'">$(BundleTestWasmAppDependsOn);_BundleAOTTestWasmAppForHelix</BundleTestWasmAppDependsOn> <RunCommand>$(WasmAppHostDir)/WasmAppHost</RunCommand> <!-- Use BundleDir here, since WasmAppDir is set in a target, and `dotnet run` reads $(Run*) without running any targets --> <RunArguments>--runtime-config $(BundleDir)/WasmTestRunner.runtimeconfig.json $(WasmHostArguments) $(StartArguments) $(WasmXHarnessMonoArgs) $(_AppArgs)</RunArguments> </PropertyGroup> <PropertyGroup Condition="'$(BuildAOTTestsOnHelix)' == 'true'"> <!-- wasm targets are not imported at all, in this case, because we run the wasm build on helix --> </PropertyGroup> <PropertyGroup Condition="'$(BuildAOTTestsOnHelix)' != 'true'"> <WasmBuildOnlyAfterPublish>true</WasmBuildOnlyAfterPublish> <!-- wasm's publish targets will trigger publish, so we shouldn't do that --> <PublishTestAsSelfContainedDependsOn /> <WasmNestedPublishAppDependsOn>PrepareForWasmBuildApp;$(WasmNestedPublishAppDependsOn)</WasmNestedPublishAppDependsOn> </PropertyGroup> <ItemGroup> <WorkloadIdForTesting Include="wasm-tools" ManifestName="Microsoft.NET.Workload.Mono.ToolChain" Version="$(PackageVersion)" VersionBand="$(SdkBandVersion)" /> <WasmExtraFilesToDeploy Condition="'$(_UseWasmSymbolicator)' == 'true'" Include="$(MonoProjectRoot)wasm\data\wasm-symbol-patterns.txt" /> <WasmExtraFilesToDeploy Condition="'$(_UseWasmSymbolicator)' == 'true'" Include="$(ArtifactsBinDir)WasmSymbolicator\$(Configuration)\$(NetCoreAppToolCurrent)\WasmSymbolicator.dll" /> </ItemGroup> <Target Name="BundleTestWasmApp" DependsOnTargets="$(BundleTestWasmAppDependsOn)" /> <UsingTask Condition="'$(BuildAOTTestsOnHelix)' == 'true'" TaskName="Microsoft.WebAssembly.Build.Tasks.GenerateAOTProps" AssemblyFile="$(WasmBuildTasksAssemblyPath)" /> <Target Name="_BundleAOTTestWasmAppForHelix" DependsOnTargets="PrepareForWasmBuildApp"> <PropertyGroup Condition="'$(IsHighAotMemoryUsageTest)' == 'true' and '$(ContinuousIntegrationBuild)' == 'true'"> <DisableParallelEmccCompile Condition="'$(DisableParallelEmccCompile)' == ''">true</DisableParallelEmccCompile> <EmccLinkOptimizationFlag Condition="'$(EmccLinkOptimizationFlag)' == ''">-O2</EmccLinkOptimizationFlag> </PropertyGroup> <PropertyGroup> <_MainAssemblyPath Condition="'%(WasmAssembliesToBundle.FileName)' == $(AssemblyName) and '%(WasmAssembliesToBundle.Extension)' == '.dll'">%(WasmAssembliesToBundle.Identity)</_MainAssemblyPath> <RuntimeConfigFilePath>$([System.IO.Path]::ChangeExtension($(_MainAssemblyPath), '.runtimeconfig.json'))</RuntimeConfigFilePath> <EmccLinkOptimizationFlag Condition="'$(EmccLinkOptimizationFlag)' == ''">-Oz -Wl,-O0 -Wl,-lto-O0</EmccLinkOptimizationFlag> </PropertyGroup> <Error Text="Item WasmAssembliesToBundle is empty. This is likely an authoring error." Condition="@(WasmAssembliesToBundle->Count()) == 0" /> <ItemGroup> <BundleFiles Include="$(WasmMainJSPath)" TargetDir="publish" /> <BundleFiles Include="@(WasmAssembliesToBundle)" TargetDir="publish\%(WasmAssembliesToBundle.RecursiveDir)" /> <BundleFiles Include="$(RuntimeConfigFilePath)" TargetDir="publish" /> <BundleFiles Include="$(MonoProjectRoot)\wasm\data\aot-tests\*" TargetDir="publish" /> </ItemGroup> <ItemGroup Condition="'$(DebuggerSupport)' == 'true'"> <!-- Add any pdb files, if available --> <_BundlePdbFiles Include="$([System.IO.Path]::ChangeExtension('%(WasmAssembliesToBundle.Identity)', '.pdb'))" /> <BundleFiles Include="@(_BundlePdbFiles)" TargetDir="publish" Condition="Exists(%(_BundlePdbFiles.Identity))" /> </ItemGroup> <!-- To recreate the original project on helix, we need to set the wasm properties also, same as the library test project. Eg. $(InvariantGlobalization) --> <ItemGroup> <_WasmPropertyNames Include="AOTMode" /> <_WasmPropertyNames Include="AssemblyName" /> <_WasmPropertyNames Include="DisableParallelAot" /> <_WasmPropertyNames Include="DisableParallelEmccCompile" /> <_WasmPropertyNames Include="EmccCompileOptimizationFlag" /> <_WasmPropertyNames Include="EmccLinkOptimizationFlag" /> <_WasmPropertyNames Include="IncludeSatelliteAssembliesInVFS" /> <_WasmPropertyNames Include="InvariantGlobalization" /> <_WasmPropertyNames Include="WasmBuildNative" /> <_WasmPropertyNames Include="WasmDebugLevel" /> <_WasmPropertyNames Include="WasmDedup" /> <_WasmPropertyNames Include="WasmLinkIcalls" /> <_WasmPropertyNames Include="WasmNativeStrip" /> <_WasmPropertyNames Include="WasmEnableES6" /> <_WasmPropertyNames Include="_WasmDevel" /> <_WasmPropertyNames Include="_WasmStrictVersionMatch" /> <_WasmPropertyNames Include="WasmEmitSymbolMap" /> <_WasmPropertiesToPass Include="$(%(_WasmPropertyNames.Identity))" Name="%(_WasmPropertyNames.Identity)" ConditionToUse__="%(_WasmPropertyNames.ConditionToUse__)" /> <_WasmVFSFilesToCopy Include="@(WasmFilesToIncludeInFileSystem)" /> <_WasmVFSFilesToCopy TargetPath="%(FileName)%(Extension)" Condition="'%(_WasmVFSFilesToCopy.TargetPath)' == ''" /> <_WasmExtraFilesToCopy Include="@(WasmExtraFilesToDeploy)" /> <_WasmExtraFilesToCopy TargetPath="%(FileName)%(Extension)" Condition="'%(_WasmExtraFilesToCopy.TargetPath)' == ''" /> <!-- Example of passing items to the project <_WasmItemsToPass Include="@(BundleFiles)" OriginalItemName__="BundleFiles" ConditionToUse__="'$(Foo)' != 'true'" /> --> <_WasmItemsToPass Include="@(_AOT_InternalForceInterpretAssemblies)" OriginalItemName__="_AOT_InternalForceInterpretAssemblies" /> </ItemGroup> <!-- This file gets imported by the project file on helix --> <GenerateAOTProps Properties="@(_WasmPropertiesToPass)" Items="@(_WasmItemsToPass)" OutputFile="$(BundleDir)publish\ProxyProjectForAOTOnHelix.props" /> <Copy SourceFiles="@(BundleFiles)" DestinationFolder="$(BundleDir)%(TargetDir)" /> <Copy SourceFiles="@(_WasmVFSFilesToCopy)" DestinationFiles="$(BundleDir)\vfsFiles\%(_WasmVFSFilesToCopy.TargetPath)" /> <Copy SourceFiles="@(_WasmExtraFilesToCopy)" DestinationFiles="$(BundleDir)\extraFiles\%(_WasmExtraFilesToCopy.TargetPath)" /> </Target> <Target Name="PrepareForWasmBuildApp"> <PropertyGroup> <WasmAppDir>$(BundleDir)</WasmAppDir> <WasmMainAssemblyFileName Condition="'$(WasmMainAssemblyFileName)' == ''">WasmTestRunner.dll</WasmMainAssemblyFileName> <WasmMainJSPath Condition="'$(WasmMainJSPath)' == ''">$(MonoProjectRoot)\wasm\test-main.js</WasmMainJSPath> <WasmInvariantGlobalization>$(InvariantGlobalization)</WasmInvariantGlobalization> <WasmGenerateRunV8Script>true</WasmGenerateRunV8Script> <WasmNativeDebugSymbols Condition="'$(DebuggerSupport)' == 'true' and '$(WasmNativeDebugSymbols)' == ''">true</WasmNativeDebugSymbols> <WasmDebugLevel Condition="'$(DebuggerSupport)' == 'true' and '$(WasmDebugLevel)' == ''">-1</WasmDebugLevel> </PropertyGroup> <ItemGroup Condition="'$(IncludeSatelliteAssembliesInVFS)' == 'true' and '$(BuildAOTTestsOnHelix)' != 'true'"> <_SatelliteAssemblies Include="$(PublishDir)*\*.resources.dll" /> <_SatelliteAssemblies CultureName="$([System.IO.Directory]::GetParent('%(Identity)').Name)" /> <_SatelliteAssemblies TargetPath="%(CultureName)\%(FileName)%(Extension)" /> <WasmFilesToIncludeInFileSystem Include="@(_SatelliteAssemblies)" /> </ItemGroup> <ItemGroup> <WasmAssembliesToBundle Include="$(PublishDir)\**\*.dll" Condition="'$(BuildAOTTestsOnHelix)' == 'true'" /> <WasmFilesToIncludeInFileSystem Include="@(ContentWithTargetPath)" /> <_CopyLocalPaths Include="@(PublishItemsOutputGroupOutputs)" Condition="'%(PublishItemsOutputGroupOutputs.BuildReference)' == 'true' and !$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.resources.dll'))" /> <_CopyLocalPaths TargetPath="%(_CopyLocalPaths.RelativePath)" Condition="'%(_CopyLocalPaths.RelativePath)' != ''" /> <_CopyLocalPaths TargetPath="%(FileName)%(Extension)" Condition="'%(_CopyLocalPaths.RelativePath)' == ''" /> <WasmFilesToIncludeInFileSystem Include="@(_CopyLocalPaths)" /> <!-- Include files specified by test projects from publish dir --> <WasmFilesToIncludeInFileSystem Include="$(PublishDir)%(WasmFilesToIncludeFromPublishDir.Identity)" TargetPath="%(WasmFilesToIncludeFromPublishDir.Identity)" Condition="'%(WasmFilesToIncludeFromPublishDir.Identity)' != ''" /> </ItemGroup> </Target> <!-- linker automatically picks up the .pdb files, but they are not added to the publish list. Add them explicitly here, so they can be used with WasmAppBuilder --> <Target Name="AddPdbFilesToPublishList" AfterTargets="ILLink" Condition="'$(DebuggerSupport)' == 'true'"> <ItemGroup> <_PdbFilesToCheck Include="$([System.IO.Path]::ChangeExtension('%(ResolvedFileToPublish.Identity)', '.pdb'))" Condition="'%(ResolvedFileToPublish.Extension)' == '.dll'" /> <ResolvedFileToPublish Include="@(_PdbFilesToCheck)" Condition="Exists(%(_PdbFilesToCheck.Identity))" RelativePath="%(_PdbFilesToCheck.FileName)%(_PdbFilesToCheck.Extension)" /> </ItemGroup> </Target> <Target Name="ProvideNodeNpmRestoreScripts" BeforeTargets="GenerateRunScript"> <!-- Combine optional alias on all NodeNpmModule and trim separator where alias is empty --> <ItemGroup> <_NodeNpmModuleString Include="%(NodeNpmModule.Identity):%(NodeNpmModule.Alias)" /> <_NodeNpmModuleStringTrimmed Include="@(_NodeNpmModuleString->Trim(':'))" /> </ItemGroup> <PropertyGroup> <NodeNpmModuleString>@(_NodeNpmModuleStringTrimmed, ',')</NodeNpmModuleString> </PropertyGroup> <!-- Restore NPM packages --> <ItemGroup Condition="'$(OS)' != 'Windows_NT'"> <SetScriptCommands Include="if [[ &quot;$SCENARIO&quot; == &quot;WasmTestOnNodeJs&quot; || &quot;$SCENARIO&quot; == &quot;wasmtestonnodejs&quot; ]]; then export WasmXHarnessMonoArgs=&quot;$WasmXHarnessMonoArgs --setenv=NPM_MODULES=$(NodeNpmModuleString)&quot;; fi" /> <RunScriptCommands Include="if [[ &quot;$SCENARIO&quot; == &quot;WasmTestOnNodeJs&quot; || &quot;$SCENARIO&quot; == &quot;wasmtestonnodejs&quot; ]]; then npm ci; fi" /> </ItemGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> <SetScriptCommands Include="if /I [%SCENARIO%]==[WasmTestOnNodeJS] ( set &quot;WasmXHarnessMonoArgs=%WasmXHarnessMonoArgs% --setenv=NPM_MODULES^=$(NodeNpmModuleString)&quot; )" /> <RunScriptCommands Include="if /I [%SCENARIO%]==[WasmTestOnNodeJS] ( call npm ci )" /> </ItemGroup> </Target> </Project>
1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/pretest.proj
<Project Sdk="Microsoft.Build.Traversal"> <Import Project="Sdk.props" Sdk="Microsoft.DotNet.SharedFramework.Sdk" /> <PropertyGroup Condition="'$(ContinuousIntegrationBuild)' != 'true'"> <!-- Create an intermediate runsettings file to enable VSTest discovery. --> <EnableRunSettingsSupport>true</EnableRunSettingsSupport> <CreateIntermediateRunSettingsFile>true</CreateIntermediateRunSettingsFile> <CreateVsCodeRunSettingsFile>true</CreateVsCodeRunSettingsFile> </PropertyGroup> <PropertyGroup> <IsPackable>false</IsPackable> </PropertyGroup> <!-- Explicitly build the externals.csproj project first to create the PlatformManifest for the targeting and runtimepack before the test runners which consume that asset are built. --> <ItemGroup> <ExternalsProject Include="externals.csproj" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''" /> <ProjectReference Include="@(ExternalsProject)" Condition="'$(MSBuildRestoreSessionId)' != ''" /> <ProjectReference Include="$(CommonTestPath)AppleTestRunner\AppleTestRunner.csproj" Condition="'$(TargetOS)' == 'MacCatalyst' or '$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'iOSSimulator' or '$(TargetOS)' == 'tvOS' or '$(TargetOS)' == 'tvOSSimulator'"/> <ProjectReference Include="$(CommonTestPath)AndroidTestRunner\AndroidTestRunner.csproj" Condition="'$(TargetOS)' == 'Android'" /> <ProjectReference Include="$(CommonTestPath)WasmTestRunner\WasmTestRunner.csproj" Condition="'$(TargetOS)' == 'Browser'" /> <!-- needed to test workloads for wasm --> <ProjectReference Include="$(InstallerProjectRoot)pkg\sfx\Microsoft.NETCore.App\Microsoft.NETCore.App.Runtime.sfxproj" Pack="true" Condition="'$(TargetOS)' == 'Browser'" /> </ItemGroup> <Target Name="BuildExternalsProject" BeforeTargets="Build"> <MSBuild Targets="Build" Projects="@(ExternalsProject)" Properties="$(TraversalGlobalProperties)" /> </Target> <Target Name="CreateIntermediateRunSettingsFile" DependsOnTargets="GenerateRunSettingsFile" BeforeTargets="Build" Condition="'$(CreateIntermediateRunSettingsFile)' == 'true'" /> <Target Name="GetSharedFrameworkRuntimeFiles"> <ItemGroup> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.Android.so" /> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.OpenSsl.so" /> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.Apple.dylib" /> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.OpenSsl.dylib" /> <SharedFrameworkRuntimeFile Include="$(MicrosoftNetCoreAppRuntimePackRidLibTfmDir)*; $(MicrosoftNetCoreAppRuntimePackNativeDir)*; @(ManualRuntimePackNativeFile->'$(MicrosoftNetCoreAppRuntimePackNativeDir)%(Identity)')" TargetPath="runtimes/" /> </ItemGroup> </Target> <!-- Generate the runtime pack's PlatformManifest --> <UsingTask TaskName="GenerateFileVersionProps" AssemblyFile="$(InstallerTasksAssemblyPath)"/> <Target Name="GenerateFileVersionPropsRuntimePack" DependsOnTargets="GetSharedFrameworkRuntimeFiles" AfterTargets="BuildExternalsProject" Inputs="@(SharedFrameworkRuntimeFile)" Outputs="$(MicrosoftNetCoreAppRuntimePackDir)data\PlatformManifest.txt" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <GenerateFileVersionProps Files="@(SharedFrameworkRuntimeFile)" PackageId="$(MicrosoftNetCoreAppFrameworkName).Runtime.$(PackageRID)" PackageVersion="$(ProductVersion)" PlatformManifestFile="$(MicrosoftNetCoreAppRuntimePackDir)data\PlatformManifest.txt" PreferredPackages="$(MicrosoftNetCoreAppFrameworkName).Runtime.$(PackageRID)" PermitDllAndExeFilesLackingFileVersion="true" /> </Target> <!-- Generate the ref pack's PlatformManifest --> <Target Name="GenerateFileVersionPropsRefPack" DependsOnTargets="GetSharedFrameworkRuntimeFiles" AfterTargets="BuildExternalsProject" Inputs="@(SharedFrameworkRuntimeFile)" Outputs="$(MicrosoftNetCoreAppRefPackDataDir)PlatformManifest.txt" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <GenerateFileVersionProps Files="@(SharedFrameworkRuntimeFile)" PackageId="$(MicrosoftNetCoreAppFrameworkName).Ref" PackageVersion="$(ProductVersion)" PlatformManifestFile="$(MicrosoftNetCoreAppRefPackDataDir)PlatformManifest.txt" PreferredPackages="$(MicrosoftNetCoreAppFrameworkName).Ref" PermitDllAndExeFilesLackingFileVersion="true" /> </Target> <!-- Generate the shared framework's deps.json --> <UsingTask TaskName="GenerateTestSharedFrameworkDepsFile" AssemblyFile="$(InstallerTasksAssemblyPath)"/> <Target Name="GenerateTestSharedFrameworkAssets" AfterTargets="BuildExternalsProject" Inputs="$(NetCoreAppCurrentTestHostSharedFrameworkPath)*.*" Outputs="$(NetCoreAppCurrentTestHostSharedFrameworkPath)$(MicrosoftNetCoreAppFrameworkName).deps.json" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <!-- Shared framework deps file generation. Produces a test shared-framework deps file. --> <GenerateTestSharedFrameworkDepsFile SharedFrameworkDirectory="$(NetCoreAppCurrentTestHostSharedFrameworkPath)" RuntimeGraphFiles="$(RuntimeIdGraphDefinitionFile)" TargetRuntimeIdentifier="$(PackageRID)" /> </Target> <Target Name="GetRuntimePackFiles"> <ItemGroup> <RuntimePackLibFile Include="$(MicrosoftNetCoreAppRuntimePackRidLibTfmDir)*.*"> <TargetPath>runtimes/$(PackageRID)/lib/$(NetCoreAppCurrent)</TargetPath> </RuntimePackLibFile> <RuntimePackNativeFile Include="$(MicrosoftNetCoreAppRuntimePackNativeDir)*.*"> <TargetPath>runtimes/$(PackageRID)/native</TargetPath> <IsNative>true</IsNative> </RuntimePackNativeFile> <!-- Clear the IsNative flag on System.Private.CoreLib given that it is present in native dir but it is actually managed --> <RuntimePackNativeFile IsNative="" Condition="'%(FileName)%(Extension)' == 'System.Private.CoreLib.dll'" /> </ItemGroup> <!-- We need to set this metadata in a separate ItemGroup than when the Items are initially populated in order to have access to the Extension metadata. --> <ItemGroup> <RuntimePackLibFile> <IsSymbolFile Condition="'%(Extension)' == '.pdb'">true</IsSymbolFile> </RuntimePackLibFile> <RuntimePackNativeFile> <IsSymbolFile Condition="'%(Extension)' == '.pdb'">true</IsSymbolFile> </RuntimePackNativeFile> </ItemGroup> </Target> <!-- Generate the runtime pack's RuntimeList.xml --> <UsingTask TaskName="CreateFrameworkListFile" AssemblyFile="$(DotNetSharedFrameworkTaskFile)"/> <Target Name="GenerateRuntimeListFile" DependsOnTargets="GetRuntimePackFiles" AfterTargets="BuildExternalsProject" Inputs="@(RuntimePackLibFile);@(RuntimePackNativeFile)" Outputs="$(MicrosoftNetCoreAppRuntimePackDir)data\RuntimeList.xml" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <ItemGroup> <FrameworkListRootAttribute Include="Name" Value="$(NetCoreAppCurrentBrandName)" /> <FrameworkListRootAttribute Include="TargetFrameworkIdentifier" Value="$(NetCoreAppCurrentIdentifier)" /> <FrameworkListRootAttribute Include="TargetFrameworkVersion" Value="$(NetCoreAppCurrentVersion)" /> <FrameworkListRootAttribute Include="FrameworkName" Value="$(MicrosoftNetCoreAppFrameworkName)" /> </ItemGroup> <CreateFrameworkListFile Files="@(RuntimePackLibFile);@(RuntimePackNativeFile)" TargetFile="$(MicrosoftNetCoreAppRuntimePackDir)data\RuntimeList.xml" TargetFilePrefixes="ref/;runtimes/" RootAttributes="@(FrameworkListRootAttribute)" /> </Target> <Import Project="Sdk.targets" Sdk="Microsoft.DotNet.SharedFramework.Sdk" /> </Project>
<Project Sdk="Microsoft.Build.Traversal"> <Import Project="Sdk.props" Sdk="Microsoft.DotNet.SharedFramework.Sdk" /> <PropertyGroup Condition="'$(ContinuousIntegrationBuild)' != 'true'"> <!-- Create an intermediate runsettings file to enable VSTest discovery. --> <EnableRunSettingsSupport>true</EnableRunSettingsSupport> <CreateIntermediateRunSettingsFile>true</CreateIntermediateRunSettingsFile> <CreateVsCodeRunSettingsFile>true</CreateVsCodeRunSettingsFile> </PropertyGroup> <PropertyGroup> <IsPackable>false</IsPackable> </PropertyGroup> <!-- Explicitly build the externals.csproj project first to create the PlatformManifest for the targeting and runtimepack before the test runners which consume that asset are built. --> <ItemGroup> <ExternalsProject Include="externals.csproj" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''" /> <ProjectReference Include="@(ExternalsProject)" Condition="'$(MSBuildRestoreSessionId)' != ''" /> <ProjectReference Include="$(CommonTestPath)AppleTestRunner\AppleTestRunner.csproj" Condition="'$(TargetOS)' == 'MacCatalyst' or '$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'iOSSimulator' or '$(TargetOS)' == 'tvOS' or '$(TargetOS)' == 'tvOSSimulator'"/> <ProjectReference Include="$(CommonTestPath)AndroidTestRunner\AndroidTestRunner.csproj" Condition="'$(TargetOS)' == 'Android'" /> <ProjectReference Include="$(CommonTestPath)WasmTestRunner\WasmTestRunner.csproj" Condition="'$(TargetOS)' == 'Browser'" /> <ProjectReference Include="$(MonoProjectRoot)wasm\symbolicator\WasmSymbolicator.csproj" Condition="'$(TargetOS)' == 'Browser'" /> <!-- needed to test workloads for wasm --> <ProjectReference Include="$(InstallerProjectRoot)pkg\sfx\Microsoft.NETCore.App\Microsoft.NETCore.App.Runtime.sfxproj" Pack="true" Condition="'$(TargetOS)' == 'Browser'" /> </ItemGroup> <Target Name="BuildExternalsProject" BeforeTargets="Build"> <MSBuild Targets="Build" Projects="@(ExternalsProject)" Properties="$(TraversalGlobalProperties)" /> </Target> <Target Name="CreateIntermediateRunSettingsFile" DependsOnTargets="GenerateRunSettingsFile" BeforeTargets="Build" Condition="'$(CreateIntermediateRunSettingsFile)' == 'true'" /> <Target Name="GetSharedFrameworkRuntimeFiles"> <ItemGroup> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.Android.so" /> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.OpenSsl.so" /> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.Apple.dylib" /> <ManualRuntimePackNativeFile Include="System.Security.Cryptography.Native.OpenSsl.dylib" /> <SharedFrameworkRuntimeFile Include="$(MicrosoftNetCoreAppRuntimePackRidLibTfmDir)*; $(MicrosoftNetCoreAppRuntimePackNativeDir)*; @(ManualRuntimePackNativeFile->'$(MicrosoftNetCoreAppRuntimePackNativeDir)%(Identity)')" TargetPath="runtimes/" /> </ItemGroup> </Target> <!-- Generate the runtime pack's PlatformManifest --> <UsingTask TaskName="GenerateFileVersionProps" AssemblyFile="$(InstallerTasksAssemblyPath)"/> <Target Name="GenerateFileVersionPropsRuntimePack" DependsOnTargets="GetSharedFrameworkRuntimeFiles" AfterTargets="BuildExternalsProject" Inputs="@(SharedFrameworkRuntimeFile)" Outputs="$(MicrosoftNetCoreAppRuntimePackDir)data\PlatformManifest.txt" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <GenerateFileVersionProps Files="@(SharedFrameworkRuntimeFile)" PackageId="$(MicrosoftNetCoreAppFrameworkName).Runtime.$(PackageRID)" PackageVersion="$(ProductVersion)" PlatformManifestFile="$(MicrosoftNetCoreAppRuntimePackDir)data\PlatformManifest.txt" PreferredPackages="$(MicrosoftNetCoreAppFrameworkName).Runtime.$(PackageRID)" PermitDllAndExeFilesLackingFileVersion="true" /> </Target> <!-- Generate the ref pack's PlatformManifest --> <Target Name="GenerateFileVersionPropsRefPack" DependsOnTargets="GetSharedFrameworkRuntimeFiles" AfterTargets="BuildExternalsProject" Inputs="@(SharedFrameworkRuntimeFile)" Outputs="$(MicrosoftNetCoreAppRefPackDataDir)PlatformManifest.txt" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <GenerateFileVersionProps Files="@(SharedFrameworkRuntimeFile)" PackageId="$(MicrosoftNetCoreAppFrameworkName).Ref" PackageVersion="$(ProductVersion)" PlatformManifestFile="$(MicrosoftNetCoreAppRefPackDataDir)PlatformManifest.txt" PreferredPackages="$(MicrosoftNetCoreAppFrameworkName).Ref" PermitDllAndExeFilesLackingFileVersion="true" /> </Target> <!-- Generate the shared framework's deps.json --> <UsingTask TaskName="GenerateTestSharedFrameworkDepsFile" AssemblyFile="$(InstallerTasksAssemblyPath)"/> <Target Name="GenerateTestSharedFrameworkAssets" AfterTargets="BuildExternalsProject" Inputs="$(NetCoreAppCurrentTestHostSharedFrameworkPath)*.*" Outputs="$(NetCoreAppCurrentTestHostSharedFrameworkPath)$(MicrosoftNetCoreAppFrameworkName).deps.json" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <!-- Shared framework deps file generation. Produces a test shared-framework deps file. --> <GenerateTestSharedFrameworkDepsFile SharedFrameworkDirectory="$(NetCoreAppCurrentTestHostSharedFrameworkPath)" RuntimeGraphFiles="$(RuntimeIdGraphDefinitionFile)" TargetRuntimeIdentifier="$(PackageRID)" /> </Target> <Target Name="GetRuntimePackFiles"> <ItemGroup> <RuntimePackLibFile Include="$(MicrosoftNetCoreAppRuntimePackRidLibTfmDir)*.*"> <TargetPath>runtimes/$(PackageRID)/lib/$(NetCoreAppCurrent)</TargetPath> </RuntimePackLibFile> <RuntimePackNativeFile Include="$(MicrosoftNetCoreAppRuntimePackNativeDir)*.*"> <TargetPath>runtimes/$(PackageRID)/native</TargetPath> <IsNative>true</IsNative> </RuntimePackNativeFile> <!-- Clear the IsNative flag on System.Private.CoreLib given that it is present in native dir but it is actually managed --> <RuntimePackNativeFile IsNative="" Condition="'%(FileName)%(Extension)' == 'System.Private.CoreLib.dll'" /> </ItemGroup> <!-- We need to set this metadata in a separate ItemGroup than when the Items are initially populated in order to have access to the Extension metadata. --> <ItemGroup> <RuntimePackLibFile> <IsSymbolFile Condition="'%(Extension)' == '.pdb'">true</IsSymbolFile> </RuntimePackLibFile> <RuntimePackNativeFile> <IsSymbolFile Condition="'%(Extension)' == '.pdb'">true</IsSymbolFile> </RuntimePackNativeFile> </ItemGroup> </Target> <!-- Generate the runtime pack's RuntimeList.xml --> <UsingTask TaskName="CreateFrameworkListFile" AssemblyFile="$(DotNetSharedFrameworkTaskFile)"/> <Target Name="GenerateRuntimeListFile" DependsOnTargets="GetRuntimePackFiles" AfterTargets="BuildExternalsProject" Inputs="@(RuntimePackLibFile);@(RuntimePackNativeFile)" Outputs="$(MicrosoftNetCoreAppRuntimePackDir)data\RuntimeList.xml" Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''"> <ItemGroup> <FrameworkListRootAttribute Include="Name" Value="$(NetCoreAppCurrentBrandName)" /> <FrameworkListRootAttribute Include="TargetFrameworkIdentifier" Value="$(NetCoreAppCurrentIdentifier)" /> <FrameworkListRootAttribute Include="TargetFrameworkVersion" Value="$(NetCoreAppCurrentVersion)" /> <FrameworkListRootAttribute Include="FrameworkName" Value="$(MicrosoftNetCoreAppFrameworkName)" /> </ItemGroup> <CreateFrameworkListFile Files="@(RuntimePackLibFile);@(RuntimePackNativeFile)" TargetFile="$(MicrosoftNetCoreAppRuntimePackDir)data\RuntimeList.xml" TargetFilePrefixes="ref/;runtimes/" RootAttributes="@(FrameworkListRootAttribute)" /> </Target> <Import Project="Sdk.targets" Sdk="Microsoft.DotNet.SharedFramework.Sdk" /> </Project>
1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/sample/wasm/Directory.Build.props
<Project> <PropertyGroup> <!-- These need to be set here because the root Directory.Build.props sets up the intermediate path early --> <Configuration>Release</Configuration> <OutputType>Exe</OutputType> <TargetOS>browser</TargetOS> <TargetArchitecture>wasm</TargetArchitecture> <RuntimeIdentifier>browser-wasm</RuntimeIdentifier> </PropertyGroup> <Import Project="..\Directory.Build.props"/> <PropertyGroup> <OutputPath>bin</OutputPath> <WasmAppDir>$(MSBuildProjectDirectory)\bin\$(Configuration)\AppBundle\</WasmAppDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <WasmNativeStrip>false</WasmNativeStrip> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' != 'Debug'"> <!-- Runtime feature defaults to trim unnecessary code --> <EventSourceSupport>false</EventSourceSupport> <UseSystemResourceKeys>true</UseSystemResourceKeys> <EnableUnsafeUTF7Encoding>false</EnableUnsafeUTF7Encoding> <HttpActivityPropagationSupport>false</HttpActivityPropagationSupport> <DebuggerSupport>false</DebuggerSupport> </PropertyGroup> <!-- Import late, so properties like $(ArtifactsBinDir) are set --> <Import Project="$(MonoProjectRoot)wasm\build\WasmApp.InTree.props" /> </Project>
<Project> <PropertyGroup> <!-- These need to be set here because the root Directory.Build.props sets up the intermediate path early --> <Configuration>Release</Configuration> <OutputType>Exe</OutputType> <TargetOS>browser</TargetOS> <TargetArchitecture>wasm</TargetArchitecture> <RuntimeIdentifier>browser-wasm</RuntimeIdentifier> </PropertyGroup> <Import Project="..\Directory.Build.props"/> <PropertyGroup> <OutputPath>bin</OutputPath> <WasmAppDir>$(MSBuildProjectDirectory)\bin\$(Configuration)\AppBundle\</WasmAppDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <WasmNativeStrip>false</WasmNativeStrip> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)' != 'Debug'"> <!-- Runtime feature defaults to trim unnecessary code --> <EventSourceSupport>false</EventSourceSupport> <UseSystemResourceKeys>true</UseSystemResourceKeys> <EnableUnsafeUTF7Encoding>false</EnableUnsafeUTF7Encoding> <HttpActivityPropagationSupport>false</HttpActivityPropagationSupport> <DebuggerSupport>false</DebuggerSupport> <WasmEmitSymbolMap>true</WasmEmitSymbolMap> </PropertyGroup> <!-- Import late, so properties like $(ArtifactsBinDir) are set --> <Import Project="$(MonoProjectRoot)wasm\build\WasmApp.InTree.props" /> </Project>
1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/README.md
# Building This depends on `emsdk` to be installed. ## emsdk on macOS * You can run `make provision-wasm`, which will install it to `$reporoot/src/mono/wasm/emsdk` . Note: Irrespective of `$(EMSDK_PATH)`'s value, `provision-wasm` will always install into `$reporoot/src/mono/wasm/emsdk`. `EMSDK_PATH` is set to `$reporoot/src/mono/wasm/emsdk` by default, by the Makefile. Note: `EMSDK_PATH` is set by default in `src/mono/wasm/Makefile`, so building targets from that will have it set. But you might need to set it manually if you are directly using the `dotnet build`, or `build.sh`. * Alternatively you can install **correct version** yourself from the [Emscripten SDK guide](https://emscripten.org/docs/getting_started/downloads.html). Do not install `latest` but rather specific version e.g. `./emsdk install 2.0.23`. See [emscripten-version.txt](./emscripten-version.txt) Make sure to set `EMSDK_PATH` variable, whenever building, or running tests for wasm. ## Building on macOS * To build the whole thing, with libraries: `make build-all` * To build just the runtime (useful when doing incremental builds with only runtime changes): `make runtime` **Note:** Additional msbuild arguments can be passed with: `make build-all MSBUILD_ARGS="/p:a=b"` ## emsdk on Windows Windows build [requirements](https://github.com/dotnet/runtime/blob/main/docs/workflow/requirements/windows-requirements.md) If `EMSDK_PATH` is not set, the `emsdk` should be provisioned automatically during the build. **Note:** The EMSDK has an implicit dependency on Python for it to be initialized. A consequence of this is that if the system doesn't have Python installed prior to attempting a build, the automatic provisioning will fail and be in an invalid state. Therefore, if Python needs to be installed after a build attempt the `$reporoot/src/mono/wasm/emsdk` directory should be manually deleted and then a rebuild attempted. ## Bulding on Windows * To build everything `build.cmd -os Browser -subset mono+libs` in the repo top level directory. # Running tests ## Installation of JavaScript engines The latest engines can be installed with jsvu (JavaScript engine Version Updater https://github.com/GoogleChromeLabs/jsvu) ### macOS * Install npm with brew: `brew install npm` * Install jsvu with npm: `npm install jsvu -g` * Run jsvu and install `v8`, `SpiderMonkey`, or `JavaScriptCore` engines: `jsvu` Add `~/.jsvu` to your `PATH`: `export PATH="${HOME}/.jsvu:${PATH}"` ### Windows * Install node/npm from https://nodejs.org/en/ and add its npm and nodejs directories to the `PATH` environment variable * * Install jsvu with npm: `npm install jsvu -g` * Run jsvu and install `v8`, `SpiderMonkey`, or `JavaScriptCore` engines: `jsvu` * Add `~/.jsvu` to the `PATH` environment variable ## Libraries tests Library tests can be run with js engines: `v8`, `SpiderMonkey`,or `JavaScriptCore`: ### macOS * `v8`: `make run-tests-v8-$(lib_name)` * SpiderMonkey: `make run-tests-sm-$(lib_name)` * JavaScriptCore: `make run-tests-jsc-$(lib_name)` * Or default: `make run-tests-$(lib_name)`. This runs the tests with `v8`. For example, for `System.Collections.Concurrent`: `make run-tests-v8-System.Collections.Concurrent` ### Windows Library tests on windows can be run as described in [testing-libraries](https://github.com/dotnet/runtime/blob/main/docs/workflow/testing/libraries/testing.md#testing-libraries) documentation. Without setting additional properties, it will run tests for all libraries on `v8` engine: `.\build.cmd libs.tests -test -os browser` * `JSEngine` property can be used to specify which engine to use. Right now `v8` and `SpiderMonkey` engines can be used. Examples of running tests for individual libraries: `.\dotnet.cmd build /t:Test /p:TargetOS=Browser src\libraries\System.Collections.Concurrent\tests` `.\dotnet.cmd build /t:Test /p:TargetOS=Browser /p:JSEngine="SpiderMonkey" src\libraries\System.Text.Json\tests` ### Browser tests on macOS Or they can be run with a browser (Chrome): `make run-browser-tests-$(lib_name)` Note: this needs `chromedriver`, and `Google Chrome` to be installed. For example, for `System.Collections.Concurrent`: `make run-browser-tests-System.Collections.Concurrent` These tests are run with `xharness wasm test-browser`, for running on the browser. And `xharness wasm test` for others. The wrapper script used to actually run these tests, accepts: `$XHARNESS_COMMAND`, which defaults to `test`. `$XHARNESS_CLI_PATH` (see next section) ### Using a local build of xharness * set `XHARNESS_CLI_PATH=/path/to/xharness/artifacts/bin/Microsoft.DotNet.XHarness.CLI/Debug/netcoreapp3.1/Microsoft.DotNet.XHarness.CLI.dll` **Note:** Additional msbuild arguments can be passed with: `make .. MSBUILD_ARGS="/p:a=b"` ## Debugger tests on macOS Debugger tests need `Google Chrome` to be installed. `make run-debugger-tests` To run a test with `FooBar` in the name: `make run-debugger-tests TEST_FILTER=FooBar` (See https://docs.microsoft.com/en-us/dotnet/core/testing/selective-unit-tests?pivots=xunit for filter options) Additional arguments for `dotnet test` can be passed via `MSBUILD_ARGS` or `TEST_ARGS`. For example `MSBUILD_ARGS="/p:WasmDebugLevel=5"`. Though only one of `TEST_ARGS`, or `TEST_FILTER` can be used at a time. - Chrome can be installed for testing by setting `InstallChromeForDebuggerTests=true` when building the tests. ## Run samples The samples in `src/mono/sample/wasm` can be build and run like this: * console Hello world sample `dotnet build /t:RunSample console-v8-cjs/Wasm.Console.V8.CJS.Sample.csproj` * browser TestMeaning sample `dotnet build /t:RunSample browser/Wasm.Browser.CJS.Sample.csproj` To build and run the samples with AOT, add `/p:RunAOTCompilation=true` to the above command lines. * bench sample Also check [bench](../sample/wasm/browser-bench/README.md) sample to measure mono/wasm runtime performance. ## Templates The wasm templates, located in the `templates` directory, are templates for `dotnet new`, VS and VS for Mac. They are packaged and distributed as part of the `wasm-tools` workload. We have 2 templates, `wasmbrowser` and `wasmconsole`, for browser and console WebAssembly applications. For details about using `dotnet new` see the dotnet tool [documentation](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-new). To test changes in the templates, use `dotnet new -i <path>`. Example use of the `wasmconsole` template: > dotnet new wasmconsole > dotnet publish > cd bin/Debug/net7.0/browser-wasm/AppBundle > node main.cjs mono_wasm_runtime_ready fe00e07a-5519-4dfe-b35a-f867dbaf2e28 Hello World! Args: ## Upgrading Emscripten Bumping Emscripten version involves these steps: * update https://github.com/dotnet/runtime/blob/main/src/mono/wasm/emscripten-version.txt * bump emscripten versions in docker images in https://github.com/dotnet/dotnet-buildtools-prereqs-docker * bump emscripten in https://github.com/dotnet/emsdk * bump docker images in https://github.com/dotnet/icu, update emscripten files in eng/patches/ * update version number in docs * update `Microsoft.NET.Runtime.Emscripten.<emscripten version>.Node.win-x64` package name, version and sha hash in https://github.com/dotnet/runtime/blob/main/eng/Version.Details.xml and in https://github.com/dotnet/runtime/blob/main/eng/Versions.props. the sha is the commit hash in https://github.com/dotnet/emsdk and the package version can be found at https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet6 * update packages in the workload manifest https://github.com/dotnet/runtime/blob/main/src/mono/nuget/Microsoft.NET.Workload.Mono.Toolchain.Manifest/WorkloadManifest.json.in ## Code style * Is enforced via [eslint](https://eslint.org/) and rules are in `./.eslintrc.js` * You could check the style by running `npm run lint` in `src/mono/wasm/runtime` directory * You can install [plugin into your VS Code](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) to show you the errors as you type ## Builds on CI * For PRs, tests are generally triggered based on path changes. But if you have a change which would not trigger the relevant builds, then you can run `runtime-wasm` pipeline manually to run all of them. Comment `/azp run runtime-wasm` on the PR. ### How do I know which jobs run on CI, and when? ## PR: * `runtime-extra-platforms`, and `runtime-wasm` run only when manually triggered with a comment - `/azp run <pipeline-name>` * `runtime`, and `runtime-staging`, run jobs only when relevant paths change. And for `EAT`, and `AOT`, only smoke tests are run. * And when `runtime-wasm` is triggered manually, it runs *all* the wasm jobs completely | . | runtime | runtime-staging | runtime-extra-platforms(manual only) | runtime-wasm (manual only) | | ----------------- | -------------------- | --------------- | ------------------------------------ | ------- | | libtests | linux: all, only-pc | windows: all, only-pc | linux+windows: all, only-pc | linux+windows: all, always | | libtests eat | linux: smoke, only-pc | - | linux: all, only-pc | linux: all, always | | libtests aot | linux: smoke, only-pc | windows: smoke, only-pc | linux+windows: all, only-pc | linux+windows: all, always | | high resource aot | none | none | linux+windows: all, only-pc | linux+windows: all, always | | Wasm.Build.Tests | linux: only-pc | windows: only-pc | linux+windows: only-pc | linux+windows | | Debugger tests | - | linux+windows: only-pc | linux+windows: only-pc | linux+windows | | Runtime tests | linux: only-pc | - | linux: only-pc | linux | * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT. ## Rolling build (twice a day): * `runtime`, and `runtime-staging`, run all the wasm jobs unconditionally, but `EAT`, and `AOT` still run only smoke tests. * `runtime-extra-platforms` also runs by default. And it runs only the cases not covered by the above two pipelines. * jobs w/o `only-pc` are always run | . | runtime | runtime-staging | runtime-extra-platforms (always run) | runtime-wasm (manual only) | | ----------------- | ------------- | --------------- | ------------------------------------ | ------ | | libtests | linux: all(v8/chr) | windows: all | none | N/A | | libtests eat | linux: smoke | - | linux: all | | | libtests aot | linux: smoke | windows: smoke | linux+windows: all | | | high resource aot | none | none | linux+windows: all | | | | | | | | | Wasm.Build.Tests | linux: always | windows: always | none | | | Debugger tests | - | linux+windows: always | none | | | Runtime tests | linux: always | - | none | | * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT.
# Building This depends on `emsdk` to be installed. ## emsdk on macOS * You can run `make provision-wasm`, which will install it to `$reporoot/src/mono/wasm/emsdk` . Note: Irrespective of `$(EMSDK_PATH)`'s value, `provision-wasm` will always install into `$reporoot/src/mono/wasm/emsdk`. `EMSDK_PATH` is set to `$reporoot/src/mono/wasm/emsdk` by default, by the Makefile. Note: `EMSDK_PATH` is set by default in `src/mono/wasm/Makefile`, so building targets from that will have it set. But you might need to set it manually if you are directly using the `dotnet build`, or `build.sh`. * Alternatively you can install **correct version** yourself from the [Emscripten SDK guide](https://emscripten.org/docs/getting_started/downloads.html). Do not install `latest` but rather specific version e.g. `./emsdk install 2.0.23`. See [emscripten-version.txt](./emscripten-version.txt) Make sure to set `EMSDK_PATH` variable, whenever building, or running tests for wasm. ## Building on macOS * To build the whole thing, with libraries: `make build-all` * To build just the runtime (useful when doing incremental builds with only runtime changes): `make runtime` **Note:** Additional msbuild arguments can be passed with: `make build-all MSBUILD_ARGS="/p:a=b"` ## emsdk on Windows Windows build [requirements](https://github.com/dotnet/runtime/blob/main/docs/workflow/requirements/windows-requirements.md) If `EMSDK_PATH` is not set, the `emsdk` should be provisioned automatically during the build. **Note:** The EMSDK has an implicit dependency on Python for it to be initialized. A consequence of this is that if the system doesn't have Python installed prior to attempting a build, the automatic provisioning will fail and be in an invalid state. Therefore, if Python needs to be installed after a build attempt the `$reporoot/src/mono/wasm/emsdk` directory should be manually deleted and then a rebuild attempted. ## Bulding on Windows * To build everything `build.cmd -os Browser -subset mono+libs` in the repo top level directory. # Running tests ## Installation of JavaScript engines The latest engines can be installed with jsvu (JavaScript engine Version Updater https://github.com/GoogleChromeLabs/jsvu) ### macOS * Install npm with brew: `brew install npm` * Install jsvu with npm: `npm install jsvu -g` * Run jsvu and install `v8`, `SpiderMonkey`, or `JavaScriptCore` engines: `jsvu` Add `~/.jsvu` to your `PATH`: `export PATH="${HOME}/.jsvu:${PATH}"` ### Windows * Install node/npm from https://nodejs.org/en/ and add its npm and nodejs directories to the `PATH` environment variable * * Install jsvu with npm: `npm install jsvu -g` * Run jsvu and install `v8`, `SpiderMonkey`, or `JavaScriptCore` engines: `jsvu` * Add `~/.jsvu` to the `PATH` environment variable ## Libraries tests Library tests can be run with js engines: `v8`, `SpiderMonkey`,or `JavaScriptCore`: ### macOS * `v8`: `make run-tests-v8-$(lib_name)` * SpiderMonkey: `make run-tests-sm-$(lib_name)` * JavaScriptCore: `make run-tests-jsc-$(lib_name)` * Or default: `make run-tests-$(lib_name)`. This runs the tests with `v8`. For example, for `System.Collections.Concurrent`: `make run-tests-v8-System.Collections.Concurrent` ### Windows Library tests on windows can be run as described in [testing-libraries](https://github.com/dotnet/runtime/blob/main/docs/workflow/testing/libraries/testing.md#testing-libraries) documentation. Without setting additional properties, it will run tests for all libraries on `v8` engine: `.\build.cmd libs.tests -test -os browser` * `JSEngine` property can be used to specify which engine to use. Right now `v8` and `SpiderMonkey` engines can be used. Examples of running tests for individual libraries: `.\dotnet.cmd build /t:Test /p:TargetOS=Browser src\libraries\System.Collections.Concurrent\tests` `.\dotnet.cmd build /t:Test /p:TargetOS=Browser /p:JSEngine="SpiderMonkey" src\libraries\System.Text.Json\tests` ### Browser tests on macOS Or they can be run with a browser (Chrome): `make run-browser-tests-$(lib_name)` Note: this needs `chromedriver`, and `Google Chrome` to be installed. For example, for `System.Collections.Concurrent`: `make run-browser-tests-System.Collections.Concurrent` These tests are run with `xharness wasm test-browser`, for running on the browser. And `xharness wasm test` for others. The wrapper script used to actually run these tests, accepts: `$XHARNESS_COMMAND`, which defaults to `test`. `$XHARNESS_CLI_PATH` (see next section) ### Using a local build of xharness * set `XHARNESS_CLI_PATH=/path/to/xharness/artifacts/bin/Microsoft.DotNet.XHarness.CLI/Debug/netcoreapp3.1/Microsoft.DotNet.XHarness.CLI.dll` **Note:** Additional msbuild arguments can be passed with: `make .. MSBUILD_ARGS="/p:a=b"` ### Symbolicating traces Exceptions thrown after the runtime starts get symbolicating from js itself. Exceptions before that, like asserts containing native traces get symbolicated by xharness using `src/mono/wasm/symbolicator`. If you need to symbolicate some traces manually, then you need the corresponding `dotnet.js.symbols` file. Then: ``` src/mono/wasm/symbolicator$ dotnet run /path/to/dotnet.js.symbols /path/to/file/with/traces ``` When not relinking, or not building with AOT, you can find `dotnet.js.symbols` in the runtime pack. ## Debugger tests on macOS Debugger tests need `Google Chrome` to be installed. `make run-debugger-tests` To run a test with `FooBar` in the name: `make run-debugger-tests TEST_FILTER=FooBar` (See https://docs.microsoft.com/en-us/dotnet/core/testing/selective-unit-tests?pivots=xunit for filter options) Additional arguments for `dotnet test` can be passed via `MSBUILD_ARGS` or `TEST_ARGS`. For example `MSBUILD_ARGS="/p:WasmDebugLevel=5"`. Though only one of `TEST_ARGS`, or `TEST_FILTER` can be used at a time. - Chrome can be installed for testing by setting `InstallChromeForDebuggerTests=true` when building the tests. ## Run samples The samples in `src/mono/sample/wasm` can be build and run like this: * console Hello world sample `dotnet build /t:RunSample console-v8-cjs/Wasm.Console.V8.CJS.Sample.csproj` * browser TestMeaning sample `dotnet build /t:RunSample browser/Wasm.Browser.CJS.Sample.csproj` To build and run the samples with AOT, add `/p:RunAOTCompilation=true` to the above command lines. * bench sample Also check [bench](../sample/wasm/browser-bench/README.md) sample to measure mono/wasm runtime performance. ## Templates The wasm templates, located in the `templates` directory, are templates for `dotnet new`, VS and VS for Mac. They are packaged and distributed as part of the `wasm-tools` workload. We have 2 templates, `wasmbrowser` and `wasmconsole`, for browser and console WebAssembly applications. For details about using `dotnet new` see the dotnet tool [documentation](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-new). To test changes in the templates, use `dotnet new -i <path>`. Example use of the `wasmconsole` template: > dotnet new wasmconsole > dotnet publish > cd bin/Debug/net7.0/browser-wasm/AppBundle > node main.cjs mono_wasm_runtime_ready fe00e07a-5519-4dfe-b35a-f867dbaf2e28 Hello World! Args: ## Upgrading Emscripten Bumping Emscripten version involves these steps: * update https://github.com/dotnet/runtime/blob/main/src/mono/wasm/emscripten-version.txt * bump emscripten versions in docker images in https://github.com/dotnet/dotnet-buildtools-prereqs-docker * bump emscripten in https://github.com/dotnet/emsdk * bump docker images in https://github.com/dotnet/icu, update emscripten files in eng/patches/ * update version number in docs * update `Microsoft.NET.Runtime.Emscripten.<emscripten version>.Node.win-x64` package name, version and sha hash in https://github.com/dotnet/runtime/blob/main/eng/Version.Details.xml and in https://github.com/dotnet/runtime/blob/main/eng/Versions.props. the sha is the commit hash in https://github.com/dotnet/emsdk and the package version can be found at https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet6 * update packages in the workload manifest https://github.com/dotnet/runtime/blob/main/src/mono/nuget/Microsoft.NET.Workload.Mono.Toolchain.Manifest/WorkloadManifest.json.in ## Code style * Is enforced via [eslint](https://eslint.org/) and rules are in `./.eslintrc.js` * You could check the style by running `npm run lint` in `src/mono/wasm/runtime` directory * You can install [plugin into your VS Code](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) to show you the errors as you type ## Builds on CI * For PRs, tests are generally triggered based on path changes. But if you have a change which would not trigger the relevant builds, then you can run `runtime-wasm` pipeline manually to run all of them. Comment `/azp run runtime-wasm` on the PR. ### How do I know which jobs run on CI, and when? ## PR: * `runtime-extra-platforms`, and `runtime-wasm` run only when manually triggered with a comment - `/azp run <pipeline-name>` * `runtime`, and `runtime-staging`, run jobs only when relevant paths change. And for `EAT`, and `AOT`, only smoke tests are run. * And when `runtime-wasm` is triggered manually, it runs *all* the wasm jobs completely | . | runtime | runtime-staging | runtime-extra-platforms(manual only) | runtime-wasm (manual only) | | ----------------- | -------------------- | --------------- | ------------------------------------ | ------- | | libtests | linux: all, only-pc | windows: all, only-pc | linux+windows: all, only-pc | linux+windows: all, always | | libtests eat | linux: smoke, only-pc | - | linux: all, only-pc | linux: all, always | | libtests aot | linux: smoke, only-pc | windows: smoke, only-pc | linux+windows: all, only-pc | linux+windows: all, always | | high resource aot | none | none | linux+windows: all, only-pc | linux+windows: all, always | | Wasm.Build.Tests | linux: only-pc | windows: only-pc | linux+windows: only-pc | linux+windows | | Debugger tests | - | linux+windows: only-pc | linux+windows: only-pc | linux+windows | | Runtime tests | linux: only-pc | - | linux: only-pc | linux | * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT. ## Rolling build (twice a day): * `runtime`, and `runtime-staging`, run all the wasm jobs unconditionally, but `EAT`, and `AOT` still run only smoke tests. * `runtime-extra-platforms` also runs by default. And it runs only the cases not covered by the above two pipelines. * jobs w/o `only-pc` are always run | . | runtime | runtime-staging | runtime-extra-platforms (always run) | runtime-wasm (manual only) | | ----------------- | ------------- | --------------- | ------------------------------------ | ------ | | libtests | linux: all(v8/chr) | windows: all | none | N/A | | libtests eat | linux: smoke | - | linux: all | | | libtests aot | linux: smoke | windows: smoke | linux+windows: all | | | high resource aot | none | none | linux+windows: all | | | | | | | | | Wasm.Build.Tests | linux: always | windows: always | none | | | Debugger tests | - | linux+windows: always | none | | | Runtime tests | linux: always | - | none | | * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT.
1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/runtime/startup.ts
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. import { AllAssetEntryTypes, mono_assert, AssetEntry, CharPtrNull, DotnetModule, GlobalizationMode, MonoConfig, MonoConfigError, wasm_type_symbol, MonoObject } from "./types"; import { ENVIRONMENT_IS_ESM, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, INTERNAL, locateFile, Module, MONO, requirePromise, runtimeHelpers } from "./imports"; import cwraps from "./cwraps"; import { mono_wasm_raise_debug_event, mono_wasm_runtime_ready } from "./debug"; import { mono_wasm_globalization_init, mono_wasm_load_icu_data } from "./icu"; import { toBase64StringImpl } from "./base64"; import { mono_wasm_init_aot_profiler, mono_wasm_init_coverage_profiler } from "./profiler"; import { mono_wasm_load_bytes_into_heap } from "./buffers"; import { bind_runtime_method, get_method, _create_primitive_converters } from "./method-binding"; import { find_corlib_class } from "./class-loader"; import { VoidPtr, CharPtr } from "./types/emscripten"; import { DotnetPublicAPI } from "./exports"; import { mono_on_abort } from "./run"; import { mono_wasm_new_root } from "./roots"; import { init_crypto } from "./crypto-worker"; export let runtime_is_initialized_resolve: Function; export let runtime_is_initialized_reject: Function; export const mono_wasm_runtime_is_initialized = new Promise((resolve, reject) => { runtime_is_initialized_resolve = resolve; runtime_is_initialized_reject = reject; }); let ctx: DownloadAssetsContext | null = null; export function configure_emscripten_startup(module: DotnetModule, exportedAPI: DotnetPublicAPI): void { // HACK: Emscripten expects us to provide it a fully qualified path where it can find // our main script so that it can be loaded from inside of workers, because workers // have their paths relative to the root instead of relative to our location // In the browser we can create a hyperlink and set its href to a relative URL, // and the browser will convert it into an absolute one for us if ( (typeof (globalThis.document) === "object") && (typeof (globalThis.document.createElement) === "function") ) { // blazor injects a module preload link element for dotnet.[version].[sha].js const blazorDotNetJS = Array.from(document.head.getElementsByTagName("link")).filter(elt => elt.rel !== undefined && elt.rel == "modulepreload" && elt.href !== undefined && elt.href.indexOf("dotnet") != -1 && elt.href.indexOf(".js") != -1); if (blazorDotNetJS.length == 1) { const hr = blazorDotNetJS[0].href; console.log("determined url of main script to be " + hr); (<any>module)["mainScriptUrlOrBlob"] = hr; } else { const temp = globalThis.document.createElement("a"); temp.href = "dotnet.js"; console.log("determined url of main script to be " + temp.href); (<any>module)["mainScriptUrlOrBlob"] = temp.href; } } // these could be overriden on DotnetModuleConfig if (!module.preInit) { module.preInit = []; } else if (typeof module.preInit === "function") { module.preInit = [module.preInit]; } if (!module.preRun) { module.preRun = []; } else if (typeof module.preRun === "function") { module.preRun = [module.preRun]; } if (!module.postRun) { module.postRun = []; } else if (typeof module.postRun === "function") { module.postRun = [module.postRun]; } // when user set configSrc or config, we are running our default startup sequence. if (module.configSrc || module.config) { // execution order == [0] == // - default or user Module.instantiateWasm (will start downloading dotnet.wasm) // - all user Module.preInit // execution order == [1] == module.preInit.push(mono_wasm_pre_init); // - download Module.config from configSrc // - download assets like DLLs // execution order == [2] == // - all user Module.preRun callbacks // execution order == [3] == // - user Module.onRuntimeInitialized callback // execution order == [4] == module.postRun.unshift(mono_wasm_after_runtime_initialized); // - load DLLs into WASM memory // - apply globalization and other env variables // - call mono_wasm_load_runtime // execution order == [5] == // - all user Module.postRun callbacks // execution order == [6] == module.ready = module.ready.then(async () => { // mono_wasm_runtime_is_initialized promise is resolved when finalize_startup is done await mono_wasm_runtime_is_initialized; // - here we resolve the promise returned by createDotnetRuntime export return exportedAPI; // - any code after createDotnetRuntime is executed now }); } // Otherwise startup sequence is up to user code, like Blazor if (!module.onAbort) { module.onAbort = () => mono_on_abort; } } async function mono_wasm_pre_init(): Promise<void> { const moduleExt = Module as DotnetModule; Module.addRunDependency("mono_wasm_pre_init"); // wait for locateFile setup on NodeJs if (ENVIRONMENT_IS_NODE && ENVIRONMENT_IS_ESM) { await requirePromise; } init_crypto(); if (moduleExt.configSrc) { try { // sets MONO.config implicitly await mono_wasm_load_config(moduleExt.configSrc); } catch (err: any) { runtime_is_initialized_reject(err); throw err; } if (moduleExt.onConfigLoaded) { try { await moduleExt.onConfigLoaded(<MonoConfig>runtimeHelpers.config); } catch (err: any) { Module.printErr("MONO_WASM: onConfigLoaded () failed: " + err); Module.printErr("MONO_WASM: Stacktrace: \n"); Module.printErr(err.stack); runtime_is_initialized_reject(err); throw err; } } } if (moduleExt.config) { try { // start downloading assets asynchronously // next event of emscripten would bre triggered by last `removeRunDependency` await mono_download_assets(Module.config); } catch (err: any) { runtime_is_initialized_reject(err); throw err; } } Module.removeRunDependency("mono_wasm_pre_init"); } function mono_wasm_after_runtime_initialized(): void { if (!Module.config || Module.config.isError) { return; } finalize_assets(Module.config); finalize_startup(Module.config); } // Set environment variable NAME to VALUE // Should be called before mono_load_runtime_and_bcl () in most cases export function mono_wasm_setenv(name: string, value: string): void { cwraps.mono_wasm_setenv(name, value); } export function mono_wasm_set_runtime_options(options: string[]): void { if (!Array.isArray(options)) throw new Error("Expected runtime_options to be an array of strings"); const argv = Module._malloc(options.length * 4); let aindex = 0; for (let i = 0; i < options.length; ++i) { const option = options[i]; if (typeof (option) !== "string") throw new Error("Expected runtime_options to be an array of strings"); Module.setValue(<any>argv + (aindex * 4), cwraps.mono_wasm_strdup(option), "i32"); aindex += 1; } cwraps.mono_wasm_parse_runtime_options(options.length, argv); } // this need to be run only after onRuntimeInitialized event, when the memory is ready function _handle_fetched_asset(asset: AssetEntry, url?: string) { mono_assert(ctx, "Context is expected"); mono_assert(asset.buffer, "asset.buffer is expected"); const bytes = new Uint8Array(asset.buffer); if (ctx.tracing) console.log(`MONO_WASM: Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`); const virtualName: string = typeof (asset.virtual_path) === "string" ? asset.virtual_path : asset.name; let offset: VoidPtr | null = null; switch (asset.behavior) { case "resource": case "assembly": ctx.loaded_files.push({ url: url, file: virtualName }); // falls through case "heap": case "icu": offset = mono_wasm_load_bytes_into_heap(bytes); ctx.loaded_assets[virtualName] = [offset, bytes.length]; break; case "vfs": { // FIXME const lastSlash = virtualName.lastIndexOf("/"); let parentDirectory = (lastSlash > 0) ? virtualName.substr(0, lastSlash) : null; let fileName = (lastSlash > 0) ? virtualName.substr(lastSlash + 1) : virtualName; if (fileName.startsWith("/")) fileName = fileName.substr(1); if (parentDirectory) { if (ctx.tracing) console.log(`MONO_WASM: Creating directory '${parentDirectory}'`); Module.FS_createPath( "/", parentDirectory, true, true // fixme: should canWrite be false? ); } else { parentDirectory = "/"; } if (ctx.tracing) console.log(`MONO_WASM: Creating file '${fileName}' in directory '${parentDirectory}'`); if (!mono_wasm_load_data_archive(bytes, parentDirectory)) { Module.FS_createDataFile( parentDirectory, fileName, bytes, true /* canRead */, true /* canWrite */, true /* canOwn */ ); } break; } default: throw new Error(`Unrecognized asset behavior:${asset.behavior}, for asset ${asset.name}`); } if (asset.behavior === "assembly") { const hasPpdb = cwraps.mono_wasm_add_assembly(virtualName, offset!, bytes.length); if (!hasPpdb) { const index = ctx.loaded_files.findIndex(element => element.file == virtualName); ctx.loaded_files.splice(index, 1); } } else if (asset.behavior === "icu") { if (!mono_wasm_load_icu_data(offset!)) Module.printErr(`MONO_WASM: Error loading ICU asset ${asset.name}`); } else if (asset.behavior === "resource") { cwraps.mono_wasm_add_satellite_assembly(virtualName, asset.culture!, offset!, bytes.length); } } function _apply_configuration_from_args(config: MonoConfig) { const envars = (config.environment_variables || {}); if (typeof (envars) !== "object") throw new Error("Expected config.environment_variables to be unset or a dictionary-style object"); for (const k in envars) { const v = envars![k]; if (typeof (v) === "string") mono_wasm_setenv(k, v); else throw new Error(`Expected environment variable '${k}' to be a string but it was ${typeof v}: '${v}'`); } if (config.runtime_options) mono_wasm_set_runtime_options(config.runtime_options); if (config.aot_profiler_options) mono_wasm_init_aot_profiler(config.aot_profiler_options); if (config.coverage_profiler_options) mono_wasm_init_coverage_profiler(config.coverage_profiler_options); } function finalize_startup(config: MonoConfig | MonoConfigError | undefined): void { const globalThisAny = globalThis as any; try { if (!config || config.isError) { return; } if (config.diagnostic_tracing) { console.debug("MONO_WASM: Initializing mono runtime"); } const moduleExt = Module as DotnetModule; if (!Module.disableDotnet6Compatibility && Module.exports) { // Export emscripten defined in module through EXPORTED_RUNTIME_METHODS // Useful to export IDBFS or other similar types generally exposed as // global types when emscripten is not modularized. for (let i = 0; i < Module.exports.length; ++i) { const exportName = Module.exports[i]; const exportValue = (<any>Module)[exportName]; if (exportValue) { globalThisAny[exportName] = exportValue; } else { console.warn(`MONO_WASM: The exported symbol ${exportName} could not be found in the emscripten module`); } } } try { _apply_configuration_from_args(config); mono_wasm_globalization_init(config.globalization_mode!, config.diagnostic_tracing!); cwraps.mono_wasm_load_runtime("unused", config.debug_level || 0); runtimeHelpers.wait_for_debugger = config.wait_for_debugger; } catch (err: any) { Module.printErr("MONO_WASM: mono_wasm_load_runtime () failed: " + err); Module.printErr("MONO_WASM: Stacktrace: \n"); Module.printErr(err.stack); runtime_is_initialized_reject(err); if (ENVIRONMENT_IS_SHELL || ENVIRONMENT_IS_NODE) { const wasm_exit = cwraps.mono_wasm_exit; wasm_exit(1); } } bindings_lazy_init(); let tz; try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { //swallow } mono_wasm_setenv("TZ", tz || "UTC"); mono_wasm_runtime_ready(); //legacy config loading const argsAny: any = config; if (argsAny.loaded_cb) { try { argsAny.loaded_cb(); } catch (err: any) { Module.printErr("MONO_WASM: loaded_cb () failed: " + err); Module.printErr("MONO_WASM: Stacktrace: \n"); Module.printErr(err.stack); runtime_is_initialized_reject(err); throw err; } } if (moduleExt.onDotnetReady) { try { moduleExt.onDotnetReady(); } catch (err: any) { Module.printErr("MONO_WASM: onDotnetReady () failed: " + err); Module.printErr("MONO_WASM: Stacktrace: \n"); Module.printErr(err.stack); runtime_is_initialized_reject(err); throw err; } } runtime_is_initialized_resolve(); } catch (err: any) { Module.printErr("MONO_WASM: Error in finalize_startup: " + err); runtime_is_initialized_reject(err); throw err; } } export function bindings_lazy_init(): void { if (runtimeHelpers.mono_wasm_bindings_is_ready) return; runtimeHelpers.mono_wasm_bindings_is_ready = true; // please keep System.Runtime.InteropServices.JavaScript.Runtime.MappedType in sync (<any>Object.prototype)[wasm_type_symbol] = 0; (<any>Array.prototype)[wasm_type_symbol] = 1; (<any>ArrayBuffer.prototype)[wasm_type_symbol] = 2; (<any>DataView.prototype)[wasm_type_symbol] = 3; (<any>Function.prototype)[wasm_type_symbol] = 4; (<any>Uint8Array.prototype)[wasm_type_symbol] = 11; runtimeHelpers._box_buffer_size = 65536; runtimeHelpers._unbox_buffer_size = 65536; runtimeHelpers._box_buffer = Module._malloc(runtimeHelpers._box_buffer_size); runtimeHelpers._unbox_buffer = Module._malloc(runtimeHelpers._unbox_buffer_size); runtimeHelpers._i52_error_scratch_buffer = <any>Module._malloc(4); runtimeHelpers._class_int32 = find_corlib_class("System", "Int32"); runtimeHelpers._class_uint32 = find_corlib_class("System", "UInt32"); runtimeHelpers._class_double = find_corlib_class("System", "Double"); runtimeHelpers._class_boolean = find_corlib_class("System", "Boolean"); runtimeHelpers.bind_runtime_method = bind_runtime_method; const bindingAssembly = INTERNAL.BINDING_ASM; const binding_fqn_asm = bindingAssembly.substring(bindingAssembly.indexOf("[") + 1, bindingAssembly.indexOf("]")).trim(); const binding_fqn_class = bindingAssembly.substring(bindingAssembly.indexOf("]") + 1).trim(); const binding_module = cwraps.mono_wasm_assembly_load(binding_fqn_asm); if (!binding_module) throw "Can't find bindings module assembly: " + binding_fqn_asm; if (binding_fqn_class && binding_fqn_class.length) { runtimeHelpers.runtime_classname = binding_fqn_class; if (binding_fqn_class.indexOf(".") != -1) { const idx = binding_fqn_class.lastIndexOf("."); runtimeHelpers.runtime_namespace = binding_fqn_class.substring(0, idx); runtimeHelpers.runtime_classname = binding_fqn_class.substring(idx + 1); } } runtimeHelpers.wasm_runtime_class = cwraps.mono_wasm_assembly_find_class(binding_module, runtimeHelpers.runtime_namespace, runtimeHelpers.runtime_classname); if (!runtimeHelpers.wasm_runtime_class) throw "Can't find " + binding_fqn_class + " class"; runtimeHelpers.get_call_sig_ref = get_method("GetCallSignatureRef"); if (!runtimeHelpers.get_call_sig_ref) throw "Can't find GetCallSignatureRef method"; _create_primitive_converters(); runtimeHelpers._box_root = mono_wasm_new_root<MonoObject>(); runtimeHelpers._null_root = mono_wasm_new_root<MonoObject>(); } // Initializes the runtime and loads assemblies, debug information, and other files. export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoConfigError | undefined): Promise<void> { await mono_download_assets(config); finalize_assets(config); } async function mono_download_assets(config: MonoConfig | MonoConfigError | undefined): Promise<void> { if (!config || config.isError) { return; } try { if (config.enable_debugging) config.debug_level = config.enable_debugging; config.diagnostic_tracing = config.diagnostic_tracing || false; ctx = { tracing: config.diagnostic_tracing, pending_count: config.assets.length, downloading_count: config.assets.length, fetch_all_promises: null, resolved_promises: [], loaded_assets: Object.create(null), // dlls and pdbs, used by blazor and the debugger loaded_files: [], }; // fetch_file_cb is legacy do we really want to support it ? if (!Module.imports!.fetch && typeof ((<any>config).fetch_file_cb) === "function") { runtimeHelpers.fetch = (<any>config).fetch_file_cb; } const max_parallel_downloads = 100; // in order to prevent net::ERR_INSUFFICIENT_RESOURCES if we start downloading too many files at same time let parallel_count = 0; let throttling_promise: Promise<void> | undefined = undefined; let throttling_promise_resolve: Function | undefined = undefined; const load_asset = async (config: MonoConfig, asset: AllAssetEntryTypes): Promise<MonoInitFetchResult | undefined> => { while (throttling_promise) { await throttling_promise; } ++parallel_count; if (parallel_count == max_parallel_downloads) { if (ctx!.tracing) console.log("MONO_WASM: Throttling further parallel downloads"); throttling_promise = new Promise((resolve) => { throttling_promise_resolve = resolve; }); } const moduleDependencyId = asset.name + (asset.culture || ""); Module.addRunDependency(moduleDependencyId); const sourcesList = asset.load_remote ? config.remote_sources! : [""]; let error = undefined; let result: MonoInitFetchResult | undefined = undefined; if (asset.buffer) { --ctx!.downloading_count; return { asset, attemptUrl: undefined }; } for (let sourcePrefix of sourcesList) { // HACK: Special-case because MSBuild doesn't allow "" as an attribute if (sourcePrefix === "./") sourcePrefix = ""; let attemptUrl; if (sourcePrefix.trim() === "") { if (asset.behavior === "assembly") attemptUrl = locateFile(config.assembly_root + "/" + asset.name); else if (asset.behavior === "resource") { const path = asset.culture !== "" ? `${asset.culture}/${asset.name}` : asset.name; attemptUrl = locateFile(config.assembly_root + "/" + path); } else attemptUrl = asset.name; } else { attemptUrl = sourcePrefix + asset.name; } if (asset.name === attemptUrl) { if (ctx!.tracing) console.log(`MONO_WASM: Attempting to fetch '${attemptUrl}'`); } else { if (ctx!.tracing) console.log(`MONO_WASM: Attempting to fetch '${attemptUrl}' for ${asset.name}`); } try { const response = await runtimeHelpers.fetch(attemptUrl); if (!response.ok) { error = new Error(`MONO_WASM: Fetch '${attemptUrl}' for ${asset.name} failed ${response.status} ${response.statusText}`); continue;// next source } asset.buffer = await response.arrayBuffer(); result = { asset, attemptUrl }; --ctx!.downloading_count; error = undefined; } catch (err) { error = new Error(`MONO_WASM: Fetch '${attemptUrl}' for ${asset.name} failed ${err}`); continue; //next source } if (!error) { break; // this source worked, stop searching } } --parallel_count; if (throttling_promise && parallel_count == ((max_parallel_downloads / 2) | 0)) { if (ctx!.tracing) console.log("MONO_WASM: Resuming more parallel downloads"); throttling_promise_resolve!(); throttling_promise = undefined; } if (error) { const isOkToFail = asset.is_optional || (asset.name.match(/\.pdb$/) && config.ignore_pdb_load_errors); if (!isOkToFail) throw error; } Module.removeRunDependency(moduleDependencyId); return result; }; const fetch_promises: Promise<(MonoInitFetchResult | undefined)>[] = []; // start fetching all assets in parallel for (const asset of config.assets) { fetch_promises.push(load_asset(config, asset)); } ctx.fetch_all_promises = Promise.all(fetch_promises); ctx.resolved_promises = await ctx.fetch_all_promises; } catch (err: any) { Module.printErr("MONO_WASM: Error in mono_download_assets: " + err); runtime_is_initialized_reject(err); throw err; } } function finalize_assets(config: MonoConfig | MonoConfigError | undefined): void { mono_assert(config && !config.isError, "Expected config"); mono_assert(ctx && ctx.downloading_count == 0, "Expected assets to be downloaded"); try { for (const fetch_result of ctx.resolved_promises!) { if (fetch_result) { _handle_fetched_asset(fetch_result.asset, fetch_result.attemptUrl); --ctx.pending_count; } } ctx.loaded_files.forEach(value => MONO.loaded_files.push(value.url)); if (ctx.tracing) { console.log("MONO_WASM: loaded_assets: " + JSON.stringify(ctx.loaded_assets)); console.log("MONO_WASM: loaded_files: " + JSON.stringify(ctx.loaded_files)); } } catch (err: any) { Module.printErr("MONO_WASM: Error in finalize_assets: " + err); runtime_is_initialized_reject(err); throw err; } } // used from Blazor export function mono_wasm_load_data_archive(data: Uint8Array, prefix: string): boolean { if (data.length < 8) return false; const dataview = new DataView(data.buffer); const magic = dataview.getUint32(0, true); // get magic number if (magic != 0x626c6174) { return false; } const manifestSize = dataview.getUint32(4, true); if (manifestSize == 0 || data.length < manifestSize + 8) return false; let manifest; try { const manifestContent = Module.UTF8ArrayToString(data, 8, manifestSize); manifest = JSON.parse(manifestContent); if (!(manifest instanceof Array)) return false; } catch (exc) { return false; } data = data.slice(manifestSize + 8); // Create the folder structure // /usr/share/zoneinfo // /usr/share/zoneinfo/Africa // /usr/share/zoneinfo/Asia // .. const folders = new Set<string>(); manifest.filter(m => { const file = m[0]; const last = file.lastIndexOf("/"); const directory = file.slice(0, last + 1); folders.add(directory); }); folders.forEach(folder => { Module["FS_createPath"](prefix, folder, true, true); }); for (const row of manifest) { const name = row[0]; const length = row[1]; const bytes = data.slice(0, length); Module["FS_createDataFile"](prefix, name, bytes, true, true); data = data.slice(length); } return true; } /** * Loads the mono config file (typically called mono-config.json) asynchroniously * Note: the run dependencies are so emsdk actually awaits it in order. * * @param {string} configFilePath - relative path to the config file * @throws Will throw an error if the config file loading fails */ export async function mono_wasm_load_config(configFilePath: string): Promise<void> { const module = Module; try { module.addRunDependency(configFilePath); const configRaw = await runtimeHelpers.fetch(configFilePath); const config = await configRaw.json(); runtimeHelpers.config = config; config.environment_variables = config.environment_variables || {}; config.assets = config.assets || []; config.runtime_options = config.runtime_options || []; config.globalization_mode = config.globalization_mode || GlobalizationMode.AUTO; Module.removeRunDependency(configFilePath); } catch (err) { const errMessage = `Failed to load config file ${configFilePath} ${err}`; Module.printErr(errMessage); runtimeHelpers.config = { message: errMessage, error: err, isError: true }; runtime_is_initialized_reject(err); throw err; } } export function mono_wasm_asm_loaded(assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { // Only trigger this codepath for assemblies loaded after app is ready if (runtimeHelpers.mono_wasm_runtime_is_ready !== true) return; const assembly_name_str = assembly_name !== CharPtrNull ? Module.UTF8ToString(assembly_name).concat(".dll") : ""; const assembly_data = new Uint8Array(Module.HEAPU8.buffer, assembly_ptr, assembly_len); const assembly_b64 = toBase64StringImpl(assembly_data); let pdb_b64; if (pdb_ptr) { const pdb_data = new Uint8Array(Module.HEAPU8.buffer, pdb_ptr, pdb_len); pdb_b64 = toBase64StringImpl(pdb_data); } mono_wasm_raise_debug_event({ eventName: "AssemblyLoaded", assembly_name: assembly_name_str, assembly_b64, pdb_b64 }); } export function mono_wasm_set_main_args(name: string, allRuntimeArguments: string[]): void { const main_argc = allRuntimeArguments.length + 1; const main_argv = <any>Module._malloc(main_argc * 4); let aindex = 0; Module.setValue(main_argv + (aindex * 4), cwraps.mono_wasm_strdup(name), "i32"); aindex += 1; for (let i = 0; i < allRuntimeArguments.length; ++i) { Module.setValue(main_argv + (aindex * 4), cwraps.mono_wasm_strdup(allRuntimeArguments[i]), "i32"); aindex += 1; } cwraps.mono_wasm_set_main_args(main_argc, main_argv); } type MonoInitFetchResult = { asset: AllAssetEntryTypes, attemptUrl?: string, } export type DownloadAssetsContext = { tracing: boolean, downloading_count: number, pending_count: number, fetch_all_promises: Promise<(MonoInitFetchResult | undefined)[]> | null; resolved_promises: (MonoInitFetchResult | undefined)[] | null; loaded_files: { url?: string, file: string }[], loaded_assets: { [id: string]: [VoidPtr, number] }, }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. import { AllAssetEntryTypes, mono_assert, AssetEntry, CharPtrNull, DotnetModule, GlobalizationMode, MonoConfig, MonoConfigError, wasm_type_symbol, MonoObject } from "./types"; import { ENVIRONMENT_IS_ESM, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, INTERNAL, locateFile, Module, MONO, requirePromise, runtimeHelpers } from "./imports"; import cwraps from "./cwraps"; import { mono_wasm_raise_debug_event, mono_wasm_runtime_ready } from "./debug"; import { mono_wasm_globalization_init, mono_wasm_load_icu_data } from "./icu"; import { toBase64StringImpl } from "./base64"; import { mono_wasm_init_aot_profiler, mono_wasm_init_coverage_profiler } from "./profiler"; import { mono_wasm_load_bytes_into_heap } from "./buffers"; import { bind_runtime_method, get_method, _create_primitive_converters } from "./method-binding"; import { find_corlib_class } from "./class-loader"; import { VoidPtr, CharPtr } from "./types/emscripten"; import { DotnetPublicAPI } from "./exports"; import { mono_on_abort } from "./run"; import { mono_wasm_new_root } from "./roots"; import { init_crypto } from "./crypto-worker"; export let runtime_is_initialized_resolve: Function; export let runtime_is_initialized_reject: Function; export const mono_wasm_runtime_is_initialized = new Promise((resolve, reject) => { runtime_is_initialized_resolve = resolve; runtime_is_initialized_reject = reject; }); let ctx: DownloadAssetsContext | null = null; export function configure_emscripten_startup(module: DotnetModule, exportedAPI: DotnetPublicAPI): void { // HACK: Emscripten expects us to provide it a fully qualified path where it can find // our main script so that it can be loaded from inside of workers, because workers // have their paths relative to the root instead of relative to our location // In the browser we can create a hyperlink and set its href to a relative URL, // and the browser will convert it into an absolute one for us if ( (typeof (globalThis.document) === "object") && (typeof (globalThis.document.createElement) === "function") ) { // blazor injects a module preload link element for dotnet.[version].[sha].js const blazorDotNetJS = Array.from(document.head.getElementsByTagName("link")).filter(elt => elt.rel !== undefined && elt.rel == "modulepreload" && elt.href !== undefined && elt.href.indexOf("dotnet") != -1 && elt.href.indexOf(".js") != -1); if (blazorDotNetJS.length == 1) { const hr = blazorDotNetJS[0].href; console.log("determined url of main script to be " + hr); (<any>module)["mainScriptUrlOrBlob"] = hr; } else { const temp = globalThis.document.createElement("a"); temp.href = "dotnet.js"; console.log("determined url of main script to be " + temp.href); (<any>module)["mainScriptUrlOrBlob"] = temp.href; } } // these could be overriden on DotnetModuleConfig if (!module.preInit) { module.preInit = []; } else if (typeof module.preInit === "function") { module.preInit = [module.preInit]; } if (!module.preRun) { module.preRun = []; } else if (typeof module.preRun === "function") { module.preRun = [module.preRun]; } if (!module.postRun) { module.postRun = []; } else if (typeof module.postRun === "function") { module.postRun = [module.postRun]; } // when user set configSrc or config, we are running our default startup sequence. if (module.configSrc || module.config) { // execution order == [0] == // - default or user Module.instantiateWasm (will start downloading dotnet.wasm) // - all user Module.preInit // execution order == [1] == module.preInit.push(mono_wasm_pre_init); // - download Module.config from configSrc // - download assets like DLLs // execution order == [2] == // - all user Module.preRun callbacks // execution order == [3] == // - user Module.onRuntimeInitialized callback // execution order == [4] == module.postRun.unshift(mono_wasm_after_runtime_initialized); // - load DLLs into WASM memory // - apply globalization and other env variables // - call mono_wasm_load_runtime // execution order == [5] == // - all user Module.postRun callbacks // execution order == [6] == module.ready = module.ready.then(async () => { // mono_wasm_runtime_is_initialized promise is resolved when finalize_startup is done await mono_wasm_runtime_is_initialized; // - here we resolve the promise returned by createDotnetRuntime export return exportedAPI; // - any code after createDotnetRuntime is executed now }); } // Otherwise startup sequence is up to user code, like Blazor if (!module.onAbort) { module.onAbort = () => mono_on_abort; } } async function mono_wasm_pre_init(): Promise<void> { const moduleExt = Module as DotnetModule; Module.addRunDependency("mono_wasm_pre_init"); // wait for locateFile setup on NodeJs if (ENVIRONMENT_IS_NODE && ENVIRONMENT_IS_ESM) { await requirePromise; } init_crypto(); if (moduleExt.configSrc) { try { // sets MONO.config implicitly await mono_wasm_load_config(moduleExt.configSrc); } catch (err: any) { runtime_is_initialized_reject(err); throw err; } if (moduleExt.onConfigLoaded) { try { await moduleExt.onConfigLoaded(<MonoConfig>runtimeHelpers.config); } catch (err: any) { _print_error("MONO_WASM: onConfigLoaded () failed", err); runtime_is_initialized_reject(err); throw err; } } } if (moduleExt.config) { try { // start downloading assets asynchronously // next event of emscripten would bre triggered by last `removeRunDependency` await mono_download_assets(Module.config); } catch (err: any) { runtime_is_initialized_reject(err); throw err; } } Module.removeRunDependency("mono_wasm_pre_init"); } function mono_wasm_after_runtime_initialized(): void { if (!Module.config || Module.config.isError) { return; } finalize_assets(Module.config); finalize_startup(Module.config); } function _print_error(message: string, err: any): void { Module.printErr(`${message}: ${JSON.stringify(err)}`); if (err.stack) { Module.printErr("MONO_WASM: Stacktrace: \n"); Module.printErr(err.stack); } } // Set environment variable NAME to VALUE // Should be called before mono_load_runtime_and_bcl () in most cases export function mono_wasm_setenv(name: string, value: string): void { cwraps.mono_wasm_setenv(name, value); } export function mono_wasm_set_runtime_options(options: string[]): void { if (!Array.isArray(options)) throw new Error("Expected runtime_options to be an array of strings"); const argv = Module._malloc(options.length * 4); let aindex = 0; for (let i = 0; i < options.length; ++i) { const option = options[i]; if (typeof (option) !== "string") throw new Error("Expected runtime_options to be an array of strings"); Module.setValue(<any>argv + (aindex * 4), cwraps.mono_wasm_strdup(option), "i32"); aindex += 1; } cwraps.mono_wasm_parse_runtime_options(options.length, argv); } // this need to be run only after onRuntimeInitialized event, when the memory is ready function _handle_fetched_asset(asset: AssetEntry, url?: string) { mono_assert(ctx, "Context is expected"); mono_assert(asset.buffer, "asset.buffer is expected"); const bytes = new Uint8Array(asset.buffer); if (ctx.tracing) console.log(`MONO_WASM: Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`); const virtualName: string = typeof (asset.virtual_path) === "string" ? asset.virtual_path : asset.name; let offset: VoidPtr | null = null; switch (asset.behavior) { case "resource": case "assembly": ctx.loaded_files.push({ url: url, file: virtualName }); // falls through case "heap": case "icu": offset = mono_wasm_load_bytes_into_heap(bytes); ctx.loaded_assets[virtualName] = [offset, bytes.length]; break; case "vfs": { // FIXME const lastSlash = virtualName.lastIndexOf("/"); let parentDirectory = (lastSlash > 0) ? virtualName.substr(0, lastSlash) : null; let fileName = (lastSlash > 0) ? virtualName.substr(lastSlash + 1) : virtualName; if (fileName.startsWith("/")) fileName = fileName.substr(1); if (parentDirectory) { if (ctx.tracing) console.log(`MONO_WASM: Creating directory '${parentDirectory}'`); Module.FS_createPath( "/", parentDirectory, true, true // fixme: should canWrite be false? ); } else { parentDirectory = "/"; } if (ctx.tracing) console.log(`MONO_WASM: Creating file '${fileName}' in directory '${parentDirectory}'`); if (!mono_wasm_load_data_archive(bytes, parentDirectory)) { Module.FS_createDataFile( parentDirectory, fileName, bytes, true /* canRead */, true /* canWrite */, true /* canOwn */ ); } break; } default: throw new Error(`Unrecognized asset behavior:${asset.behavior}, for asset ${asset.name}`); } if (asset.behavior === "assembly") { const hasPpdb = cwraps.mono_wasm_add_assembly(virtualName, offset!, bytes.length); if (!hasPpdb) { const index = ctx.loaded_files.findIndex(element => element.file == virtualName); ctx.loaded_files.splice(index, 1); } } else if (asset.behavior === "icu") { if (!mono_wasm_load_icu_data(offset!)) Module.printErr(`MONO_WASM: Error loading ICU asset ${asset.name}`); } else if (asset.behavior === "resource") { cwraps.mono_wasm_add_satellite_assembly(virtualName, asset.culture!, offset!, bytes.length); } } function _apply_configuration_from_args(config: MonoConfig) { const envars = (config.environment_variables || {}); if (typeof (envars) !== "object") throw new Error("Expected config.environment_variables to be unset or a dictionary-style object"); for (const k in envars) { const v = envars![k]; if (typeof (v) === "string") mono_wasm_setenv(k, v); else throw new Error(`Expected environment variable '${k}' to be a string but it was ${typeof v}: '${v}'`); } if (config.runtime_options) mono_wasm_set_runtime_options(config.runtime_options); if (config.aot_profiler_options) mono_wasm_init_aot_profiler(config.aot_profiler_options); if (config.coverage_profiler_options) mono_wasm_init_coverage_profiler(config.coverage_profiler_options); } function finalize_startup(config: MonoConfig | MonoConfigError | undefined): void { const globalThisAny = globalThis as any; try { if (!config || config.isError) { return; } if (config.diagnostic_tracing) { console.debug("MONO_WASM: Initializing mono runtime"); } const moduleExt = Module as DotnetModule; if (!Module.disableDotnet6Compatibility && Module.exports) { // Export emscripten defined in module through EXPORTED_RUNTIME_METHODS // Useful to export IDBFS or other similar types generally exposed as // global types when emscripten is not modularized. for (let i = 0; i < Module.exports.length; ++i) { const exportName = Module.exports[i]; const exportValue = (<any>Module)[exportName]; if (exportValue) { globalThisAny[exportName] = exportValue; } else { console.warn(`MONO_WASM: The exported symbol ${exportName} could not be found in the emscripten module`); } } } try { _apply_configuration_from_args(config); mono_wasm_globalization_init(config.globalization_mode!, config.diagnostic_tracing!); cwraps.mono_wasm_load_runtime("unused", config.debug_level || 0); runtimeHelpers.wait_for_debugger = config.wait_for_debugger; } catch (err: any) { _print_error("MONO_WASM: mono_wasm_load_runtime () failed", err); runtime_is_initialized_reject(err); if (ENVIRONMENT_IS_SHELL || ENVIRONMENT_IS_NODE) { const wasm_exit = cwraps.mono_wasm_exit; wasm_exit(1); } } bindings_lazy_init(); let tz; try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { //swallow } mono_wasm_setenv("TZ", tz || "UTC"); mono_wasm_runtime_ready(); //legacy config loading const argsAny: any = config; if (argsAny.loaded_cb) { try { argsAny.loaded_cb(); } catch (err: any) { _print_error("MONO_WASM: loaded_cb () failed", err); runtime_is_initialized_reject(err); throw err; } } if (moduleExt.onDotnetReady) { try { moduleExt.onDotnetReady(); } catch (err: any) { _print_error("MONO_WASM: onDotnetReady () failed", err); runtime_is_initialized_reject(err); throw err; } } runtime_is_initialized_resolve(); } catch (err: any) { _print_error("MONO_WASM: Error in finalize_startup", err); runtime_is_initialized_reject(err); throw err; } } export function bindings_lazy_init(): void { if (runtimeHelpers.mono_wasm_bindings_is_ready) return; runtimeHelpers.mono_wasm_bindings_is_ready = true; // please keep System.Runtime.InteropServices.JavaScript.Runtime.MappedType in sync (<any>Object.prototype)[wasm_type_symbol] = 0; (<any>Array.prototype)[wasm_type_symbol] = 1; (<any>ArrayBuffer.prototype)[wasm_type_symbol] = 2; (<any>DataView.prototype)[wasm_type_symbol] = 3; (<any>Function.prototype)[wasm_type_symbol] = 4; (<any>Uint8Array.prototype)[wasm_type_symbol] = 11; runtimeHelpers._box_buffer_size = 65536; runtimeHelpers._unbox_buffer_size = 65536; runtimeHelpers._box_buffer = Module._malloc(runtimeHelpers._box_buffer_size); runtimeHelpers._unbox_buffer = Module._malloc(runtimeHelpers._unbox_buffer_size); runtimeHelpers._i52_error_scratch_buffer = <any>Module._malloc(4); runtimeHelpers._class_int32 = find_corlib_class("System", "Int32"); runtimeHelpers._class_uint32 = find_corlib_class("System", "UInt32"); runtimeHelpers._class_double = find_corlib_class("System", "Double"); runtimeHelpers._class_boolean = find_corlib_class("System", "Boolean"); runtimeHelpers.bind_runtime_method = bind_runtime_method; const bindingAssembly = INTERNAL.BINDING_ASM; const binding_fqn_asm = bindingAssembly.substring(bindingAssembly.indexOf("[") + 1, bindingAssembly.indexOf("]")).trim(); const binding_fqn_class = bindingAssembly.substring(bindingAssembly.indexOf("]") + 1).trim(); const binding_module = cwraps.mono_wasm_assembly_load(binding_fqn_asm); if (!binding_module) throw "Can't find bindings module assembly: " + binding_fqn_asm; if (binding_fqn_class && binding_fqn_class.length) { runtimeHelpers.runtime_classname = binding_fqn_class; if (binding_fqn_class.indexOf(".") != -1) { const idx = binding_fqn_class.lastIndexOf("."); runtimeHelpers.runtime_namespace = binding_fqn_class.substring(0, idx); runtimeHelpers.runtime_classname = binding_fqn_class.substring(idx + 1); } } runtimeHelpers.wasm_runtime_class = cwraps.mono_wasm_assembly_find_class(binding_module, runtimeHelpers.runtime_namespace, runtimeHelpers.runtime_classname); if (!runtimeHelpers.wasm_runtime_class) throw "Can't find " + binding_fqn_class + " class"; runtimeHelpers.get_call_sig_ref = get_method("GetCallSignatureRef"); if (!runtimeHelpers.get_call_sig_ref) throw "Can't find GetCallSignatureRef method"; _create_primitive_converters(); runtimeHelpers._box_root = mono_wasm_new_root<MonoObject>(); runtimeHelpers._null_root = mono_wasm_new_root<MonoObject>(); } // Initializes the runtime and loads assemblies, debug information, and other files. export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoConfigError | undefined): Promise<void> { await mono_download_assets(config); finalize_assets(config); } async function mono_download_assets(config: MonoConfig | MonoConfigError | undefined): Promise<void> { if (!config || config.isError) { return; } try { if (config.enable_debugging) config.debug_level = config.enable_debugging; config.diagnostic_tracing = config.diagnostic_tracing || false; ctx = { tracing: config.diagnostic_tracing, pending_count: config.assets.length, downloading_count: config.assets.length, fetch_all_promises: null, resolved_promises: [], loaded_assets: Object.create(null), // dlls and pdbs, used by blazor and the debugger loaded_files: [], }; // fetch_file_cb is legacy do we really want to support it ? if (!Module.imports!.fetch && typeof ((<any>config).fetch_file_cb) === "function") { runtimeHelpers.fetch = (<any>config).fetch_file_cb; } const max_parallel_downloads = 100; // in order to prevent net::ERR_INSUFFICIENT_RESOURCES if we start downloading too many files at same time let parallel_count = 0; let throttling_promise: Promise<void> | undefined = undefined; let throttling_promise_resolve: Function | undefined = undefined; const load_asset = async (config: MonoConfig, asset: AllAssetEntryTypes): Promise<MonoInitFetchResult | undefined> => { while (throttling_promise) { await throttling_promise; } ++parallel_count; if (parallel_count == max_parallel_downloads) { if (ctx!.tracing) console.log("MONO_WASM: Throttling further parallel downloads"); throttling_promise = new Promise((resolve) => { throttling_promise_resolve = resolve; }); } const moduleDependencyId = asset.name + (asset.culture || ""); Module.addRunDependency(moduleDependencyId); const sourcesList = asset.load_remote ? config.remote_sources! : [""]; let error = undefined; let result: MonoInitFetchResult | undefined = undefined; if (asset.buffer) { --ctx!.downloading_count; return { asset, attemptUrl: undefined }; } for (let sourcePrefix of sourcesList) { // HACK: Special-case because MSBuild doesn't allow "" as an attribute if (sourcePrefix === "./") sourcePrefix = ""; let attemptUrl; if (sourcePrefix.trim() === "") { if (asset.behavior === "assembly") attemptUrl = locateFile(config.assembly_root + "/" + asset.name); else if (asset.behavior === "resource") { const path = asset.culture !== "" ? `${asset.culture}/${asset.name}` : asset.name; attemptUrl = locateFile(config.assembly_root + "/" + path); } else attemptUrl = asset.name; } else { attemptUrl = sourcePrefix + asset.name; } if (asset.name === attemptUrl) { if (ctx!.tracing) console.log(`MONO_WASM: Attempting to fetch '${attemptUrl}'`); } else { if (ctx!.tracing) console.log(`MONO_WASM: Attempting to fetch '${attemptUrl}' for ${asset.name}`); } try { const response = await runtimeHelpers.fetch(attemptUrl); if (!response.ok) { error = new Error(`MONO_WASM: Fetch '${attemptUrl}' for ${asset.name} failed ${response.status} ${response.statusText}`); continue;// next source } asset.buffer = await response.arrayBuffer(); result = { asset, attemptUrl }; --ctx!.downloading_count; error = undefined; } catch (err) { error = new Error(`MONO_WASM: Fetch '${attemptUrl}' for ${asset.name} failed ${err}`); continue; //next source } if (!error) { break; // this source worked, stop searching } } --parallel_count; if (throttling_promise && parallel_count == ((max_parallel_downloads / 2) | 0)) { if (ctx!.tracing) console.log("MONO_WASM: Resuming more parallel downloads"); throttling_promise_resolve!(); throttling_promise = undefined; } if (error) { const isOkToFail = asset.is_optional || (asset.name.match(/\.pdb$/) && config.ignore_pdb_load_errors); if (!isOkToFail) throw error; } Module.removeRunDependency(moduleDependencyId); return result; }; const fetch_promises: Promise<(MonoInitFetchResult | undefined)>[] = []; // start fetching all assets in parallel for (const asset of config.assets) { fetch_promises.push(load_asset(config, asset)); } ctx.fetch_all_promises = Promise.all(fetch_promises); ctx.resolved_promises = await ctx.fetch_all_promises; } catch (err: any) { Module.printErr("MONO_WASM: Error in mono_download_assets: " + err); runtime_is_initialized_reject(err); throw err; } } function finalize_assets(config: MonoConfig | MonoConfigError | undefined): void { mono_assert(config && !config.isError, "Expected config"); mono_assert(ctx && ctx.downloading_count == 0, "Expected assets to be downloaded"); try { for (const fetch_result of ctx.resolved_promises!) { if (fetch_result) { _handle_fetched_asset(fetch_result.asset, fetch_result.attemptUrl); --ctx.pending_count; } } ctx.loaded_files.forEach(value => MONO.loaded_files.push(value.url)); if (ctx.tracing) { console.log("MONO_WASM: loaded_assets: " + JSON.stringify(ctx.loaded_assets)); console.log("MONO_WASM: loaded_files: " + JSON.stringify(ctx.loaded_files)); } } catch (err: any) { Module.printErr("MONO_WASM: Error in finalize_assets: " + err); runtime_is_initialized_reject(err); throw err; } } // used from Blazor export function mono_wasm_load_data_archive(data: Uint8Array, prefix: string): boolean { if (data.length < 8) return false; const dataview = new DataView(data.buffer); const magic = dataview.getUint32(0, true); // get magic number if (magic != 0x626c6174) { return false; } const manifestSize = dataview.getUint32(4, true); if (manifestSize == 0 || data.length < manifestSize + 8) return false; let manifest; try { const manifestContent = Module.UTF8ArrayToString(data, 8, manifestSize); manifest = JSON.parse(manifestContent); if (!(manifest instanceof Array)) return false; } catch (exc) { return false; } data = data.slice(manifestSize + 8); // Create the folder structure // /usr/share/zoneinfo // /usr/share/zoneinfo/Africa // /usr/share/zoneinfo/Asia // .. const folders = new Set<string>(); manifest.filter(m => { const file = m[0]; const last = file.lastIndexOf("/"); const directory = file.slice(0, last + 1); folders.add(directory); }); folders.forEach(folder => { Module["FS_createPath"](prefix, folder, true, true); }); for (const row of manifest) { const name = row[0]; const length = row[1]; const bytes = data.slice(0, length); Module["FS_createDataFile"](prefix, name, bytes, true, true); data = data.slice(length); } return true; } /** * Loads the mono config file (typically called mono-config.json) asynchroniously * Note: the run dependencies are so emsdk actually awaits it in order. * * @param {string} configFilePath - relative path to the config file * @throws Will throw an error if the config file loading fails */ export async function mono_wasm_load_config(configFilePath: string): Promise<void> { const module = Module; try { module.addRunDependency(configFilePath); const configRaw = await runtimeHelpers.fetch(configFilePath); const config = await configRaw.json(); runtimeHelpers.config = config; config.environment_variables = config.environment_variables || {}; config.assets = config.assets || []; config.runtime_options = config.runtime_options || []; config.globalization_mode = config.globalization_mode || GlobalizationMode.AUTO; Module.removeRunDependency(configFilePath); } catch (err) { const errMessage = `Failed to load config file ${configFilePath} ${err}`; Module.printErr(errMessage); runtimeHelpers.config = { message: errMessage, error: err, isError: true }; runtime_is_initialized_reject(err); throw err; } } export function mono_wasm_asm_loaded(assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { // Only trigger this codepath for assemblies loaded after app is ready if (runtimeHelpers.mono_wasm_runtime_is_ready !== true) return; const assembly_name_str = assembly_name !== CharPtrNull ? Module.UTF8ToString(assembly_name).concat(".dll") : ""; const assembly_data = new Uint8Array(Module.HEAPU8.buffer, assembly_ptr, assembly_len); const assembly_b64 = toBase64StringImpl(assembly_data); let pdb_b64; if (pdb_ptr) { const pdb_data = new Uint8Array(Module.HEAPU8.buffer, pdb_ptr, pdb_len); pdb_b64 = toBase64StringImpl(pdb_data); } mono_wasm_raise_debug_event({ eventName: "AssemblyLoaded", assembly_name: assembly_name_str, assembly_b64, pdb_b64 }); } export function mono_wasm_set_main_args(name: string, allRuntimeArguments: string[]): void { const main_argc = allRuntimeArguments.length + 1; const main_argv = <any>Module._malloc(main_argc * 4); let aindex = 0; Module.setValue(main_argv + (aindex * 4), cwraps.mono_wasm_strdup(name), "i32"); aindex += 1; for (let i = 0; i < allRuntimeArguments.length; ++i) { Module.setValue(main_argv + (aindex * 4), cwraps.mono_wasm_strdup(allRuntimeArguments[i]), "i32"); aindex += 1; } cwraps.mono_wasm_set_main_args(main_argc, main_argv); } type MonoInitFetchResult = { asset: AllAssetEntryTypes, attemptUrl?: string, } export type DownloadAssetsContext = { tracing: boolean, downloading_count: number, pending_count: number, fetch_all_promises: Promise<(MonoInitFetchResult | undefined)[]> | null; resolved_promises: (MonoInitFetchResult | undefined)[] | null; loaded_files: { url?: string, file: string }[], loaded_assets: { [id: string]: [VoidPtr, number] }, }
1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/sln/WasmBuild.sln
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31722.452 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WasmBuildTasks", "..\..\..\tasks\WasmBuildTasks\WasmBuildTasks.csproj", "{D5BD9C0C-8A05-493E-BE45-13AF8286CD92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WasmAppBuilder", "..\..\..\tasks\WasmAppBuilder\WasmAppBuilder.csproj", "{8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MonoAOTCompiler", "..\..\..\tasks\AotCompilerTask\MonoAOTCompiler.csproj", "{A9C02284-0387-42E7-BF78-47DF13656D5E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Wasm.Build.Tests", "..\..\..\tests\BuildWasmApps\Wasm.Build.Tests\Wasm.Build.Tests.csproj", "{94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DebuggerTestSuite", "..\debugger\DebuggerTestSuite\DebuggerTestSuite.csproj", "{4C0EE027-FC30-4167-B2CF-A6D18F00E08F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BrowserDebugHost", "..\debugger\BrowserDebugHost\BrowserDebugHost.csproj", "{292A88FD-795F-467A-8801-B5B791CEF96E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BrowserDebugProxy", "..\debugger\BrowserDebugProxy\BrowserDebugProxy.csproj", "{F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WasmAppHost", "..\host\WasmAppHost.csproj", "{C7099764-EC2E-4FAF-9057-0321893DE4F8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApplyUpdateReferencedAssembly", "..\debugger\tests\ApplyUpdateReferencedAssembly\ApplyUpdateReferencedAssembly.csproj", "{75477B6F-DC8E-4002-88B8-017C992C568E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Debug|Any CPU.Build.0 = Debug|Any CPU {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Release|Any CPU.ActiveCfg = Release|Any CPU {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Release|Any CPU.Build.0 = Release|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Debug|Any CPU.Build.0 = Debug|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Release|Any CPU.ActiveCfg = Release|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Release|Any CPU.Build.0 = Release|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Debug|Any CPU.Build.0 = Debug|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Release|Any CPU.ActiveCfg = Release|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Release|Any CPU.Build.0 = Release|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Debug|Any CPU.Build.0 = Debug|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Release|Any CPU.ActiveCfg = Release|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Release|Any CPU.Build.0 = Release|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Debug|Any CPU.Build.0 = Debug|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Release|Any CPU.ActiveCfg = Release|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Release|Any CPU.Build.0 = Release|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Debug|Any CPU.Build.0 = Debug|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Release|Any CPU.ActiveCfg = Release|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Release|Any CPU.Build.0 = Release|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Release|Any CPU.Build.0 = Release|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Debug|Any CPU.Build.0 = Debug|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Release|Any CPU.ActiveCfg = Release|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Release|Any CPU.Build.0 = Release|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {2BDE8FDE-4261-4B4D-8B54-ACC88B06C8D1} EndGlobalSection EndGlobal
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31722.452 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WasmBuildTasks", "..\..\..\tasks\WasmBuildTasks\WasmBuildTasks.csproj", "{D5BD9C0C-8A05-493E-BE45-13AF8286CD92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WasmAppBuilder", "..\..\..\tasks\WasmAppBuilder\WasmAppBuilder.csproj", "{8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MonoAOTCompiler", "..\..\..\tasks\AotCompilerTask\MonoAOTCompiler.csproj", "{A9C02284-0387-42E7-BF78-47DF13656D5E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Wasm.Build.Tests", "..\..\..\tests\BuildWasmApps\Wasm.Build.Tests\Wasm.Build.Tests.csproj", "{94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DebuggerTestSuite", "..\debugger\DebuggerTestSuite\DebuggerTestSuite.csproj", "{4C0EE027-FC30-4167-B2CF-A6D18F00E08F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BrowserDebugHost", "..\debugger\BrowserDebugHost\BrowserDebugHost.csproj", "{292A88FD-795F-467A-8801-B5B791CEF96E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BrowserDebugProxy", "..\debugger\BrowserDebugProxy\BrowserDebugProxy.csproj", "{F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WasmAppHost", "..\host\WasmAppHost.csproj", "{C7099764-EC2E-4FAF-9057-0321893DE4F8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WasmSymbolicator", "..\symbolicator\WasmSymbolicator.csproj", "{ABC41254-EC2E-4FAF-9057-091ABF4DE4F8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApplyUpdateReferencedAssembly", "..\debugger\tests\ApplyUpdateReferencedAssembly\ApplyUpdateReferencedAssembly.csproj", "{75477B6F-DC8E-4002-88B8-017C992C568E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Debug|Any CPU.Build.0 = Debug|Any CPU {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Release|Any CPU.ActiveCfg = Release|Any CPU {D5BD9C0C-8A05-493E-BE45-13AF8286CD92}.Release|Any CPU.Build.0 = Release|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Debug|Any CPU.Build.0 = Debug|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Release|Any CPU.ActiveCfg = Release|Any CPU {8DEBFDE2-B127-46D7-92CF-EEA6D1DA2554}.Release|Any CPU.Build.0 = Release|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Debug|Any CPU.Build.0 = Debug|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Release|Any CPU.ActiveCfg = Release|Any CPU {A9C02284-0387-42E7-BF78-47DF13656D5E}.Release|Any CPU.Build.0 = Release|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Debug|Any CPU.Build.0 = Debug|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Release|Any CPU.ActiveCfg = Release|Any CPU {94E18644-B0E5-4DBB-9CE4-EA1515ACE4C2}.Release|Any CPU.Build.0 = Release|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Debug|Any CPU.Build.0 = Debug|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Release|Any CPU.ActiveCfg = Release|Any CPU {4C0EE027-FC30-4167-B2CF-A6D18F00E08F}.Release|Any CPU.Build.0 = Release|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Debug|Any CPU.Build.0 = Debug|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Release|Any CPU.ActiveCfg = Release|Any CPU {292A88FD-795F-467A-8801-B5B791CEF96E}.Release|Any CPU.Build.0 = Release|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5AE2AF5-3C30-45E3-A0C6-D962C51FE5E7}.Release|Any CPU.Build.0 = Release|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Debug|Any CPU.Build.0 = Debug|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Release|Any CPU.ActiveCfg = Release|Any CPU {75477B6F-DC8E-4002-88B8-017C992C568E}.Release|Any CPU.Build.0 = Release|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {C7099764-EC2E-4FAF-9057-0321893DE4F8}.Release|Any CPU.Build.0 = Release|Any CPU {ABC41254-EC2E-4FAF-9057-091ABF4DE4F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ABC41254-EC2E-4FAF-9057-091ABF4DE4F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {ABC41254-EC2E-4FAF-9057-091ABF4DE4F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {ABC41254-EC2E-4FAF-9057-091ABF4DE4F8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {2BDE8FDE-4261-4B4D-8B54-ACC88B06C8D1} EndGlobalSection EndGlobal
1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/test-main.js
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // -*- mode: js; js-indent-level: 4; -*- // // Run runtime tests under a JS shell or a browser // "use strict"; //glue code to deal with the differences between chrome, ch, d8, jsc and sm. const is_browser = typeof window != "undefined"; const is_node = !is_browser && typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string'; if (is_node && process.versions.node.split(".")[0] < 14) { throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}'`); } // if the engine doesn't provide a console if (typeof (console) === "undefined") { globalThis.console = { log: globalThis.print, clear: function () { } }; } const originalConsole = { log: console.log, error: console.error }; let runArgs = {}; let consoleWebSocket; let is_debugging = false; let forward_console = true; function proxyConsoleMethod(prefix, func, asJson) { return function () { try { const args = [...arguments]; let payload = args[0]; if (payload === undefined) payload = 'undefined'; else if (payload === null) payload = 'null'; else if (typeof payload === 'function') payload = payload.toString(); else if (typeof payload !== 'string') { try { payload = JSON.stringify(payload); } catch (e) { payload = payload.toString(); } } if (payload.startsWith("STARTRESULTXML")) { originalConsole.log('Sending RESULTXML') func(payload); } else if (asJson) { func(JSON.stringify({ method: prefix, payload: payload, arguments: args })); } else { func([prefix + payload, ...args.slice(1)]); } } catch (err) { originalConsole.error(`proxyConsole failed: ${err}`) } }; }; function set_exit_code(exit_code, reason) { if (reason) { if (reason instanceof Error) console.error(stringify_as_error_with_stack(reason)); else if (typeof reason == "string") console.error(reason); else console.error(JSON.stringify(reason)); } if (is_browser) { if (App.Module) { // Notify the selenium script App.Module.exit_code = exit_code; } //Tell xharness WasmBrowserTestRunner what was the exit code const tests_done_elem = document.createElement("label"); tests_done_elem.id = "tests_done"; tests_done_elem.innerHTML = exit_code.toString(); document.body.appendChild(tests_done_elem); if (forward_console) { const stop_when_ws_buffer_empty = () => { if (consoleWebSocket.bufferedAmount == 0) { // tell xharness WasmTestMessagesProcessor we are done. // note this sends last few bytes into the same WS console.log("WASM EXIT " + exit_code); } else { setTimeout(stop_when_ws_buffer_empty, 100); } }; stop_when_ws_buffer_empty(); } else { console.log("WASM EXIT " + exit_code); } } else if (App && App.INTERNAL) { App.INTERNAL.mono_wasm_exit(exit_code); } } function stringify_as_error_with_stack(err) { if (!err) return ""; // FIXME: if (App && App.INTERNAL) return App.INTERNAL.mono_wasm_stringify_as_error_with_stack(err); if (err.stack) return err.stack; if (typeof err == "string") return err; return JSON.stringify(err); } function initRunArgs() { // set defaults runArgs.applicationArguments = runArgs.applicationArguments === undefined ? [] : runArgs.applicationArguments; runArgs.profilers = runArgs.profilers === undefined ? [] : runArgs.profilers; runArgs.workingDirectory = runArgs.workingDirectory === undefined ? '/' : runArgs.workingDirectory; runArgs.environment_variables = runArgs.environment_variables === undefined ? {} : runArgs.environment_variables; runArgs.runtimeArgs = runArgs.runtimeArgs === undefined ? [] : runArgs.runtimeArgs; runArgs.enableGC = runArgs.enableGC === undefined ? true : runArgs.enableGC; runArgs.diagnosticTracing = runArgs.diagnosticTracing === undefined ? false : runArgs.diagnosticTracing; runArgs.debugging = runArgs.debugging === undefined ? false : runArgs.debugging; // default'ing to true for tests, unless debugging runArgs.forwardConsole = runArgs.forwardConsole === undefined ? !runArgs.debugging : runArgs.forwardConsole; } function processQueryArguments(incomingArguments) { initRunArgs(); console.log("Incoming arguments: " + incomingArguments.join(' ')); while (incomingArguments && incomingArguments.length > 0) { const currentArg = incomingArguments[0]; if (currentArg.startsWith("--profile=")) { const arg = currentArg.substring("--profile=".length); runArgs.profilers.push(arg); } else if (currentArg.startsWith("--setenv=")) { const arg = currentArg.substring("--setenv=".length); const parts = arg.split('='); if (parts.length != 2) set_exit_code(1, "Error: malformed argument: '" + currentArg); runArgs.environment_variables[parts[0]] = parts[1]; } else if (currentArg.startsWith("--runtime-arg=")) { const arg = currentArg.substring("--runtime-arg=".length); runArgs.runtimeArgs.push(arg); } else if (currentArg == "--disable-on-demand-gc") { runArgs.enableGC = false; } else if (currentArg == "--diagnostic_tracing") { runArgs.diagnosticTracing = true; } else if (currentArg.startsWith("--working-dir=")) { const arg = currentArg.substring("--working-dir=".length); runArgs.workingDirectory = arg; } else if (currentArg == "--debug") { runArgs.debugging = true; } else if (currentArg == "--no-forward-console") { runArgs.forwardConsole = false; } else if (currentArg.startsWith("--fetch-random-delay=")) { const arg = currentArg.substring("--fetch-random-delay=".length); if (is_browser) { const delayms = Number.parseInt(arg) || 100; const originalFetch = globalThis.fetch; globalThis.fetch = async (url, options) => { // random sleep const ms = delayms + (Math.random() * delayms); console.log(`fetch ${url} started ${ms}`) await new Promise(resolve => setTimeout(resolve, ms)); console.log(`fetch ${url} delayed ${ms}`) const res = await originalFetch(url, options); console.log(`fetch ${url} done ${ms}`) return res; } } else { console.warn("--fetch-random-delay only works on browser") } } else { break; } incomingArguments = incomingArguments.slice(1); } runArgs.applicationArguments = incomingArguments; // cheap way to let the testing infrastructure know we're running in a browser context (or not) runArgs.environment_variables["IsBrowserDomSupported"] = is_browser.toString().toLowerCase(); runArgs.environment_variables["IsNodeJS"] = is_node.toString().toLowerCase(); return runArgs; } function applyArguments() { initRunArgs(); // set defaults is_debugging = runArgs.debugging === true; forward_console = runArgs.forwardConsole === true; console.log("Application arguments: " + runArgs.applicationArguments.join(' ')); if (forward_console) { const methods = ["debug", "trace", "warn", "info", "error"]; for (let m of methods) { if (typeof (console[m]) !== "function") { console[m] = proxyConsoleMethod(`console.${m}: `, console.log, false); } } if (is_browser) { const consoleUrl = `${window.location.origin}/console`.replace('http://', 'ws://'); consoleWebSocket = new WebSocket(consoleUrl); consoleWebSocket.onopen = function (event) { originalConsole.log("browser: Console websocket connected."); }; consoleWebSocket.onerror = function (event) { originalConsole.error(`websocket error: ${event}`, event); }; consoleWebSocket.onclose = function (event) { originalConsole.error(`websocket closed: ${event}`, event); }; const send = (msg) => { if (consoleWebSocket.readyState === WebSocket.OPEN) { consoleWebSocket.send(msg); } else { originalConsole.log(msg); } } // redirect output early, so that when emscripten starts it's already redirected for (let m of ["log", ...methods]) console[m] = proxyConsoleMethod(`console.${m}`, send, true); } } } async function loadDotnet(file) { let loadScript = undefined; if (typeof WScript !== "undefined") { // Chakra loadScript = function (file) { WScript.LoadScriptFile(file); return globalThis.createDotnetRuntime; }; } else if (is_node) { // NodeJS loadScript = async function (file) { return require(file); }; } else if (is_browser) { // vanila JS in browser loadScript = function (file) { var loaded = new Promise((resolve, reject) => { globalThis.__onDotnetRuntimeLoaded = (createDotnetRuntime) => { // this is callback we have in CJS version of the runtime resolve(createDotnetRuntime); }; import(file).then(({ default: createDotnetRuntime }) => { // this would work with ES6 default export if (createDotnetRuntime) { resolve(createDotnetRuntime); } }, reject); }); return loaded; } } else if (typeof globalThis.load !== 'undefined') { loadScript = async function (file) { globalThis.load(file) return globalThis.createDotnetRuntime; } } else { throw new Error("Unknown environment, can't load config"); } return loadScript(file); } // this can't be function because of `arguments` scope let queryArguments = []; try { if (is_node) { queryArguments = process.argv.slice(2); } else if (is_browser) { // We expect to be run by tests/runtime/run.js which passes in the arguments using http parameters const url = new URL(decodeURI(window.location)); let urlArguments = [] for (let param of url.searchParams) { if (param[0] == "arg") { urlArguments.push(param[1]); } } queryArguments = urlArguments; } else if (typeof arguments !== "undefined") { queryArguments = Array.from(arguments); } else if (typeof scriptArgs !== "undefined") { queryArguments = Array.from(scriptArgs); } else if (typeof WScript !== "undefined" && WScript.Arguments) { queryArguments = Array.from(WScript.Arguments); } } catch (e) { console.error(e); } let loadDotnetPromise = loadDotnet('./dotnet.js'); let argsPromise; if (queryArguments.length > 0) { argsPromise = Promise.resolve(processQueryArguments(queryArguments)); } else { argsPromise = fetch('/runArgs.json') .then(async (response) => { if (!response.ok) { console.debug(`could not load /args.json: ${response.status}. Ignoring`); } else { runArgs = await response.json(); console.debug(`runArgs: ${JSON.stringify(runArgs)}`); } }) .catch(error => console.error(`Failed to load args: ${stringify_as_error_with_stack(error)}`)); } if (typeof globalThis.crypto === 'undefined') { // **NOTE** this is a simple insecure polyfill for testing purposes only // /dev/random doesn't work on js shells, so define our own // See library_fs.js:createDefaultDevices () globalThis.crypto = { getRandomValues: function (buffer) { for (let i = 0; i < buffer.length; i++) buffer[i] = (Math.random() * 256) | 0; } } } if (typeof globalThis.performance === 'undefined') { if (is_node) { const { performance } = require("perf_hooks"); globalThis.performance = performance; } else { // performance.now() is used by emscripten and doesn't work in JSC globalThis.performance = { now: function () { return Date.now(); } } } } let toAbsoluteUrl = function(possiblyRelativeUrl) { return possiblyRelativeUrl; } if (is_browser) { const anchorTagForAbsoluteUrlConversions = document.createElement('a'); toAbsoluteUrl = function toAbsoluteUrl(possiblyRelativeUrl) { anchorTagForAbsoluteUrlConversions.href = possiblyRelativeUrl; return anchorTagForAbsoluteUrlConversions.href; } } Promise.all([ argsPromise, loadDotnetPromise ]).then(async ([ _, createDotnetRuntime ]) => { applyArguments(); if (is_node) { const modulesToLoad = runArgs.environment_variables["NPM_MODULES"]; if (modulesToLoad) { modulesToLoad.split(',').forEach(module => { const { 0:moduleName, 1:globalAlias } = module.split(':'); let message = `Loading npm '${moduleName}'`; let moduleExport = require(moduleName); if (globalAlias) { message += ` and attaching to global as '${globalAlias}'`; globalThis[globalAlias] = moduleExport; } else if(moduleName == "node-fetch") { message += ' and attaching to global'; globalThis.fetch = moduleExport.default; globalThis.Headers = moduleExport.Headers; globalThis.Request = moduleExport.Request; globalThis.Response = moduleExport.Response; } else if(moduleName == "node-abort-controller") { message += ' and attaching to global'; globalThis.AbortController = moduleExport.AbortController; } console.log(message); }); } } // Must be after loading npm modules. runArgs.environment_variables["IsWebSocketSupported"] = ("WebSocket" in globalThis).toString().toLowerCase(); return createDotnetRuntime(({ MONO, INTERNAL, BINDING, Module }) => ({ disableDotnet6Compatibility: true, config: null, configSrc: "./mono-config.json", locateFile: (path, prefix) => { return toAbsoluteUrl(prefix + path); }, onConfigLoaded: (config) => { if (!Module.config) { const err = new Error("Could not find ./mono-config.json. Cancelling run"); set_exit_code(1); throw err; } // Have to set env vars here to enable setting MONO_LOG_LEVEL etc. for (let variable in runArgs.environment_variables) { config.environment_variables[variable] = runArgs.environment_variables[variable]; } config.diagnostic_tracing = !!runArgs.diagnosticTracing; if (is_debugging) { if (config.debug_level == 0) config.debug_level = -1; config.wait_for_debugger = -1; } }, preRun: () => { if (!runArgs.enableGC) { INTERNAL.mono_wasm_enable_on_demand_gc(0); } }, onDotnetReady: () => { let wds = Module.FS.stat(runArgs.workingDirectory); if (wds === undefined || !Module.FS.isDir(wds.mode)) { set_exit_code(1, `Could not find working directory ${runArgs.workingDirectory}`); return; } Module.FS.chdir(runArgs.workingDirectory); App.init({ MONO, INTERNAL, BINDING, Module, runArgs }); }, onAbort: (error) => { set_exit_code(1, stringify_as_error_with_stack(new Error())); }, })) }).catch(function (err) { set_exit_code(1, "failed to load the dotnet.js file.\n" + stringify_as_error_with_stack(err)); }); const App = { init: async function ({ MONO, INTERNAL, BINDING, Module, runArgs }) { Object.assign(App, { MONO, INTERNAL, BINDING, Module, runArgs }); console.info("Initializing....."); for (let i = 0; i < runArgs.profilers.length; ++i) { const init = Module.cwrap('mono_wasm_load_profiler_' + runArgs.profilers[i], 'void', ['string']); init(""); } if (runArgs.applicationArguments.length == 0) { set_exit_code(1, "Missing required --run argument"); return; } if (runArgs.applicationArguments[0] == "--regression") { const exec_regression = Module.cwrap('mono_wasm_exec_regression', 'number', ['number', 'string']); let res = 0; try { res = exec_regression(10, runArgs.applicationArguments[1]); console.log("REGRESSION RESULT: " + res); } catch (e) { console.error("ABORT: " + e); console.error(e.stack); res = 1; } if (res) set_exit_code(1, "REGRESSION TEST FAILED"); return; } if (runArgs.runtimeArgs.length > 0) INTERNAL.mono_wasm_set_runtime_options(runArgs.runtimeArgs); if (runArgs.applicationArguments[0] == "--run") { // Run an exe if (runArgs.applicationArguments.length == 1) { set_exit_code(1, "Error: Missing main executable argument."); return; } try { const main_assembly_name = runArgs.applicationArguments[1]; const app_args = runArgs.applicationArguments.slice(2); const result = await App.MONO.mono_run_main(main_assembly_name, app_args); set_exit_code(result); } catch (error) { if (error.name != "ExitStatus") { set_exit_code(1, error); } } } else { set_exit_code(1, "Unhandled argument: " + runArgs.applicationArguments[0]); } }, /** Runs a particular test * @type {(method_name: string, args: any[]=, signature: any=) => return number} */ call_test_method: function (method_name, args, signature) { // note: arguments here is the array of arguments passsed to this function if ((arguments.length > 2) && (typeof (signature) !== "string")) throw new Error("Invalid number of arguments for call_test_method"); const fqn = "[System.Private.Runtime.InteropServices.JavaScript.Tests]System.Runtime.InteropServices.JavaScript.Tests.HelperMarshal:" + method_name; try { return App.INTERNAL.call_static_method(fqn, args || [], signature); } catch (exc) { console.error("exception thrown in", fqn); throw exc; } } }; globalThis.App = App; // Necessary as System.Runtime.InteropServices.JavaScript.Tests.MarshalTests (among others) call the App.call_test_method directly
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // -*- mode: js; js-indent-level: 4; -*- // // Run runtime tests under a JS shell or a browser // "use strict"; //glue code to deal with the differences between chrome, ch, d8, jsc and sm. const is_browser = typeof window != "undefined"; const is_node = !is_browser && typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string'; if (is_node && process.versions.node.split(".")[0] < 14) { throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}'`); } // if the engine doesn't provide a console if (typeof (console) === "undefined") { globalThis.console = { log: globalThis.print, clear: function () { } }; } const originalConsole = { log: console.log, error: console.error }; let runArgs = {}; let consoleWebSocket; let is_debugging = false; let forward_console = true; function proxyConsoleMethod(prefix, func, asJson) { return function () { try { const args = [...arguments]; let payload = args[0]; if (payload === undefined) payload = 'undefined'; else if (payload === null) payload = 'null'; else if (typeof payload === 'function') payload = payload.toString(); else if (typeof payload !== 'string') { try { payload = JSON.stringify(payload); } catch (e) { payload = payload.toString(); } } if (payload.startsWith("STARTRESULTXML")) { originalConsole.log('Sending RESULTXML') func(payload); } else if (asJson) { func(JSON.stringify({ method: prefix, payload: payload, arguments: args })); } else { func([prefix + payload, ...args.slice(1)]); } } catch (err) { originalConsole.error(`proxyConsole failed: ${err}`) } }; }; function set_exit_code(exit_code, reason) { if (reason) { if (reason instanceof Error) console.error(stringify_as_error_with_stack(reason)); else if (typeof reason == "string") console.error(reason); else console.error(JSON.stringify(reason)); } if (is_browser) { if (App.Module) { // Notify the selenium script App.Module.exit_code = exit_code; } //Tell xharness WasmBrowserTestRunner what was the exit code const tests_done_elem = document.createElement("label"); tests_done_elem.id = "tests_done"; tests_done_elem.innerHTML = exit_code.toString(); document.body.appendChild(tests_done_elem); if (forward_console) { const stop_when_ws_buffer_empty = () => { if (consoleWebSocket.bufferedAmount == 0) { // tell xharness WasmTestMessagesProcessor we are done. // note this sends last few bytes into the same WS console.log("WASM EXIT " + exit_code); } else { setTimeout(stop_when_ws_buffer_empty, 100); } }; stop_when_ws_buffer_empty(); } else { console.log("WASM EXIT " + exit_code); } } else if (App && App.INTERNAL) { App.INTERNAL.mono_wasm_exit(exit_code); } } function stringify_as_error_with_stack(err) { if (!err) return ""; // FIXME: if (App && App.INTERNAL) return App.INTERNAL.mono_wasm_stringify_as_error_with_stack(err); if (err.stack) return err.stack; if (typeof err == "string") return err; return JSON.stringify(err); } function initRunArgs() { // set defaults runArgs.applicationArguments = runArgs.applicationArguments === undefined ? [] : runArgs.applicationArguments; runArgs.profilers = runArgs.profilers === undefined ? [] : runArgs.profilers; runArgs.workingDirectory = runArgs.workingDirectory === undefined ? '/' : runArgs.workingDirectory; runArgs.environment_variables = runArgs.environment_variables === undefined ? {} : runArgs.environment_variables; runArgs.runtimeArgs = runArgs.runtimeArgs === undefined ? [] : runArgs.runtimeArgs; runArgs.enableGC = runArgs.enableGC === undefined ? true : runArgs.enableGC; runArgs.diagnosticTracing = runArgs.diagnosticTracing === undefined ? false : runArgs.diagnosticTracing; runArgs.debugging = runArgs.debugging === undefined ? false : runArgs.debugging; // default'ing to true for tests, unless debugging runArgs.forwardConsole = runArgs.forwardConsole === undefined ? !runArgs.debugging : runArgs.forwardConsole; } function processQueryArguments(incomingArguments) { initRunArgs(); console.log("Incoming arguments: " + incomingArguments.join(' ')); while (incomingArguments && incomingArguments.length > 0) { const currentArg = incomingArguments[0]; if (currentArg.startsWith("--profile=")) { const arg = currentArg.substring("--profile=".length); runArgs.profilers.push(arg); } else if (currentArg.startsWith("--setenv=")) { const arg = currentArg.substring("--setenv=".length); const parts = arg.split('='); if (parts.length != 2) set_exit_code(1, "Error: malformed argument: '" + currentArg); runArgs.environment_variables[parts[0]] = parts[1]; } else if (currentArg.startsWith("--runtime-arg=")) { const arg = currentArg.substring("--runtime-arg=".length); runArgs.runtimeArgs.push(arg); } else if (currentArg == "--disable-on-demand-gc") { runArgs.enableGC = false; } else if (currentArg == "--diagnostic_tracing") { runArgs.diagnosticTracing = true; } else if (currentArg.startsWith("--working-dir=")) { const arg = currentArg.substring("--working-dir=".length); runArgs.workingDirectory = arg; } else if (currentArg == "--debug") { runArgs.debugging = true; } else if (currentArg == "--no-forward-console") { runArgs.forwardConsole = false; } else if (currentArg.startsWith("--fetch-random-delay=")) { const arg = currentArg.substring("--fetch-random-delay=".length); if (is_browser) { const delayms = Number.parseInt(arg) || 100; const originalFetch = globalThis.fetch; globalThis.fetch = async (url, options) => { // random sleep const ms = delayms + (Math.random() * delayms); console.log(`fetch ${url} started ${ms}`) await new Promise(resolve => setTimeout(resolve, ms)); console.log(`fetch ${url} delayed ${ms}`) const res = await originalFetch(url, options); console.log(`fetch ${url} done ${ms}`) return res; } } else { console.warn("--fetch-random-delay only works on browser") } } else { break; } incomingArguments = incomingArguments.slice(1); } runArgs.applicationArguments = incomingArguments; // cheap way to let the testing infrastructure know we're running in a browser context (or not) runArgs.environment_variables["IsBrowserDomSupported"] = is_browser.toString().toLowerCase(); runArgs.environment_variables["IsNodeJS"] = is_node.toString().toLowerCase(); return runArgs; } function applyArguments() { initRunArgs(); // set defaults is_debugging = runArgs.debugging === true; forward_console = runArgs.forwardConsole === true; console.log("Application arguments: " + runArgs.applicationArguments.join(' ')); if (forward_console) { const methods = ["debug", "trace", "warn", "info", "error"]; for (let m of methods) { if (typeof (console[m]) !== "function") { console[m] = proxyConsoleMethod(`console.${m}: `, console.log, false); } } if (is_browser) { const consoleUrl = `${window.location.origin}/console`.replace('http://', 'ws://'); consoleWebSocket = new WebSocket(consoleUrl); consoleWebSocket.onopen = function (event) { originalConsole.log("browser: Console websocket connected."); }; consoleWebSocket.onerror = function (event) { originalConsole.error(`websocket error: ${event}`, event); }; consoleWebSocket.onclose = function (event) { originalConsole.error(`websocket closed: ${event}`, event); }; const send = (msg) => { if (consoleWebSocket.readyState === WebSocket.OPEN) { consoleWebSocket.send(msg); } else { originalConsole.log(msg); } } // redirect output early, so that when emscripten starts it's already redirected for (let m of ["log", ...methods]) console[m] = proxyConsoleMethod(`console.${m}`, send, true); } } } async function loadDotnet(file) { let loadScript = undefined; if (typeof WScript !== "undefined") { // Chakra loadScript = function (file) { WScript.LoadScriptFile(file); return globalThis.createDotnetRuntime; }; } else if (is_node) { // NodeJS loadScript = async function (file) { return require(file); }; } else if (is_browser) { // vanila JS in browser loadScript = function (file) { var loaded = new Promise((resolve, reject) => { globalThis.__onDotnetRuntimeLoaded = (createDotnetRuntime) => { // this is callback we have in CJS version of the runtime resolve(createDotnetRuntime); }; import(file).then(({ default: createDotnetRuntime }) => { // this would work with ES6 default export if (createDotnetRuntime) { resolve(createDotnetRuntime); } }, reject); }); return loaded; } } else if (typeof globalThis.load !== 'undefined') { loadScript = async function (file) { globalThis.load(file) return globalThis.createDotnetRuntime; } } else { throw new Error("Unknown environment, can't load config"); } return loadScript(file); } // this can't be function because of `arguments` scope let queryArguments = []; try { if (is_node) { queryArguments = process.argv.slice(2); } else if (is_browser) { // We expect to be run by tests/runtime/run.js which passes in the arguments using http parameters const url = new URL(decodeURI(window.location)); let urlArguments = [] for (let param of url.searchParams) { if (param[0] == "arg") { urlArguments.push(param[1]); } } queryArguments = urlArguments; } else if (typeof arguments !== "undefined") { queryArguments = Array.from(arguments); } else if (typeof scriptArgs !== "undefined") { queryArguments = Array.from(scriptArgs); } else if (typeof WScript !== "undefined" && WScript.Arguments) { queryArguments = Array.from(WScript.Arguments); } } catch (e) { console.error(e); } let loadDotnetPromise = loadDotnet('./dotnet.js'); let argsPromise; if (queryArguments.length > 0) { argsPromise = Promise.resolve(processQueryArguments(queryArguments)); } else { argsPromise = fetch('/runArgs.json') .then(async (response) => { if (!response.ok) { console.debug(`could not load /args.json: ${response.status}. Ignoring`); } else { runArgs = await response.json(); console.debug(`runArgs: ${JSON.stringify(runArgs)}`); } }) .catch(error => console.error(`Failed to load args: ${stringify_as_error_with_stack(error)}`)); } if (typeof globalThis.crypto === 'undefined') { // **NOTE** this is a simple insecure polyfill for testing purposes only // /dev/random doesn't work on js shells, so define our own // See library_fs.js:createDefaultDevices () globalThis.crypto = { getRandomValues: function (buffer) { for (let i = 0; i < buffer.length; i++) buffer[i] = (Math.random() * 256) | 0; } } } if (typeof globalThis.performance === 'undefined') { if (is_node) { const { performance } = require("perf_hooks"); globalThis.performance = performance; } else { // performance.now() is used by emscripten and doesn't work in JSC globalThis.performance = { now: function () { return Date.now(); } } } } let toAbsoluteUrl = function(possiblyRelativeUrl) { return possiblyRelativeUrl; } if (is_browser) { const anchorTagForAbsoluteUrlConversions = document.createElement('a'); toAbsoluteUrl = function toAbsoluteUrl(possiblyRelativeUrl) { anchorTagForAbsoluteUrlConversions.href = possiblyRelativeUrl; return anchorTagForAbsoluteUrlConversions.href; } } Promise.all([ argsPromise, loadDotnetPromise ]).then(async ([ _, createDotnetRuntime ]) => { applyArguments(); if (is_node) { const modulesToLoad = runArgs.environment_variables["NPM_MODULES"]; if (modulesToLoad) { modulesToLoad.split(',').forEach(module => { const { 0:moduleName, 1:globalAlias } = module.split(':'); let message = `Loading npm '${moduleName}'`; let moduleExport = require(moduleName); if (globalAlias) { message += ` and attaching to global as '${globalAlias}'`; globalThis[globalAlias] = moduleExport; } else if(moduleName == "node-fetch") { message += ' and attaching to global'; globalThis.fetch = moduleExport.default; globalThis.Headers = moduleExport.Headers; globalThis.Request = moduleExport.Request; globalThis.Response = moduleExport.Response; } else if(moduleName == "node-abort-controller") { message += ' and attaching to global'; globalThis.AbortController = moduleExport.AbortController; } console.log(message); }); } } // Must be after loading npm modules. runArgs.environment_variables["IsWebSocketSupported"] = ("WebSocket" in globalThis).toString().toLowerCase(); return createDotnetRuntime(({ MONO, INTERNAL, BINDING, Module }) => ({ disableDotnet6Compatibility: true, config: null, configSrc: "./mono-config.json", locateFile: (path, prefix) => { return toAbsoluteUrl(prefix + path); }, onConfigLoaded: (config) => { if (!Module.config) { const err = new Error("Could not find ./mono-config.json. Cancelling run"); set_exit_code(1); throw err; } // Have to set env vars here to enable setting MONO_LOG_LEVEL etc. for (let variable in runArgs.environment_variables) { config.environment_variables[variable] = runArgs.environment_variables[variable]; } config.diagnostic_tracing = !!runArgs.diagnosticTracing; if (is_debugging) { if (config.debug_level == 0) config.debug_level = -1; config.wait_for_debugger = -1; } }, preRun: () => { if (!runArgs.enableGC) { INTERNAL.mono_wasm_enable_on_demand_gc(0); } }, onDotnetReady: () => { let wds = Module.FS.stat(runArgs.workingDirectory); if (wds === undefined || !Module.FS.isDir(wds.mode)) { set_exit_code(1, `Could not find working directory ${runArgs.workingDirectory}`); return; } Module.FS.chdir(runArgs.workingDirectory); App.init({ MONO, INTERNAL, BINDING, Module, runArgs }); }, onAbort: (error) => { set_exit_code(1, stringify_as_error_with_stack(new Error())); }, })) }).catch(function (err) { set_exit_code(1, "failed to load the dotnet.js file.\n" + stringify_as_error_with_stack(err)); }); const App = { init: async function ({ MONO, INTERNAL, BINDING, Module, runArgs }) { Object.assign(App, { MONO, INTERNAL, BINDING, Module, runArgs }); console.info("Initializing....."); for (let i = 0; i < runArgs.profilers.length; ++i) { const init = Module.cwrap('mono_wasm_load_profiler_' + runArgs.profilers[i], 'void', ['string']); init(""); } if (runArgs.applicationArguments.length == 0) { set_exit_code(1, "Missing required --run argument"); return; } if (runArgs.applicationArguments[0] == "--regression") { const exec_regression = Module.cwrap('mono_wasm_exec_regression', 'number', ['number', 'string']); let res = 0; try { res = exec_regression(10, runArgs.applicationArguments[1]); console.log("REGRESSION RESULT: " + res); } catch (e) { console.error("ABORT: " + e); console.error(e.stack); res = 1; } if (res) set_exit_code(1, "REGRESSION TEST FAILED"); return; } if (runArgs.runtimeArgs.length > 0) INTERNAL.mono_wasm_set_runtime_options(runArgs.runtimeArgs); if (runArgs.applicationArguments[0] == "--run") { // Run an exe if (runArgs.applicationArguments.length == 1) { set_exit_code(1, "Error: Missing main executable argument."); return; } try { const main_assembly_name = runArgs.applicationArguments[1]; const app_args = runArgs.applicationArguments.slice(2); const result = await App.MONO.mono_run_main(main_assembly_name, app_args); set_exit_code(result); } catch (error) { if (error.name != "ExitStatus") { set_exit_code(1, error); } } } else { set_exit_code(1, "Unhandled argument: " + runArgs.applicationArguments[0]); } }, /** Runs a particular test * @type {(method_name: string, args: any[]=, signature: any=) => return number} */ call_test_method: function (method_name, args, signature) { // note: arguments here is the array of arguments passsed to this function if ((arguments.length > 2) && (typeof (signature) !== "string")) throw new Error("Invalid number of arguments for call_test_method"); const fqn = "[System.Private.Runtime.InteropServices.JavaScript.Tests]System.Runtime.InteropServices.JavaScript.Tests.HelperMarshal:" + method_name; try { return App.INTERNAL.call_static_method(fqn, args || [], signature); } catch (exc) { console.error("exception thrown in", fqn); throw exc; } } }; globalThis.App = App; // Necessary as System.Runtime.InteropServices.JavaScript.Tests.MarshalTests (among others) call the App.call_test_method directly
1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./eng/SubsetValidation.targets
<Project InitialTargets="FindInvalidSpecifiedSubsetNames;ReportValidSubsetList"> <!-- The imported file supports the '/p:Subset=<desired subset string>' dev build argument. Each subset has its own '<subset>Project' items so that a project in the build can depend on a whole subset, and the dependency on the subset is disregarded automatically when Subset doesn't contain it. %(ProjectToBuild.SignPhase): Indicates this project must be built before a certain signing phase. Projects can depend on 'signing/stages/Sign<stage>.proj' to wait until all projects that are part of a stage are complete. This allows the build to perform complex container signing that isn't (can't be?) supported by Arcade's single pass, such as MSIs and bundles: https://github.com/dotnet/arcade/issues/388 --> <Target Name="FindInvalidSpecifiedSubsetNames"> <ItemGroup> <SpecifiedSubsetName Include="$([MSBuild]::Unescape($(Subset.Replace('+', ';').Replace('-', ';'))))" /> <!-- MSBuild Exclude is case-insensitive, which matches intended behavior. --> <InvalidSpecifiedSubsetName Include="@(SpecifiedSubsetName)" Exclude="@(SubsetName)" /> </ItemGroup> <PropertyGroup> <UserRequestedHelp Condition="'%(InvalidSpecifiedSubsetName.Identity)' == 'help'">true</UserRequestedHelp> </PropertyGroup> </Target> <Target Name="ReportValidSubsetList" Condition="'@(InvalidSpecifiedSubsetName)' != ''"> <ItemGroup> <SubsetName Text="- %(Identity)" /> <SubsetName Text="%(Text) [only runs on demand]" Condition="'%(SubsetName.OnDemand)' == 'true'" /> <SubsetName Text="%(Text)%0A %(Description)" /> </ItemGroup> <Message Text="%0AAccepted Subset values:%0A@(SubsetName->'%(Text)', '%0A')%0A" Importance="High" /> <Error Text="Subset not recognized: @(InvalidSpecifiedSubsetName, ' ')" Condition="'$(UserRequestedHelp)' != 'true'" /> <Error Text="This is not an error. These are the available subsets. You can choose one or none at all for a full build." Condition="'$(UserRequestedHelp)' == 'true'" /> </Target> </Project>
<Project InitialTargets="FindInvalidSpecifiedSubsetNames;ReportValidSubsetList"> <!-- The imported file supports the '/p:Subset=<desired subset string>' dev build argument. Each subset has its own '<subset>Project' items so that a project in the build can depend on a whole subset, and the dependency on the subset is disregarded automatically when Subset doesn't contain it. %(ProjectToBuild.SignPhase): Indicates this project must be built before a certain signing phase. Projects can depend on 'signing/stages/Sign<stage>.proj' to wait until all projects that are part of a stage are complete. This allows the build to perform complex container signing that isn't (can't be?) supported by Arcade's single pass, such as MSIs and bundles: https://github.com/dotnet/arcade/issues/388 --> <Target Name="FindInvalidSpecifiedSubsetNames"> <ItemGroup> <SpecifiedSubsetName Include="$([MSBuild]::Unescape($(Subset.Replace('+', ';').Replace('-', ';'))))" /> <!-- MSBuild Exclude is case-insensitive, which matches intended behavior. --> <InvalidSpecifiedSubsetName Include="@(SpecifiedSubsetName)" Exclude="@(SubsetName)" /> </ItemGroup> <PropertyGroup> <UserRequestedHelp Condition="'%(InvalidSpecifiedSubsetName.Identity)' == 'help'">true</UserRequestedHelp> </PropertyGroup> </Target> <Target Name="ReportValidSubsetList" Condition="'@(InvalidSpecifiedSubsetName)' != ''"> <ItemGroup> <SubsetName Text="- %(Identity)" /> <SubsetName Text="%(Text) [only runs on demand]" Condition="'%(SubsetName.OnDemand)' == 'true'" /> <SubsetName Text="%(Text)%0A %(Description)" /> </ItemGroup> <Message Text="%0AAccepted Subset values:%0A@(SubsetName->'%(Text)', '%0A')%0A" Importance="High" /> <Error Text="Subset not recognized: @(InvalidSpecifiedSubsetName, ' ')" Condition="'$(UserRequestedHelp)' != 'true'" /> <Error Text="This is not an error. These are the available subsets. You can choose one or none at all for a full build." Condition="'$(UserRequestedHelp)' == 'true'" /> </Target> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./docs/coding-guidelines/updating-ref-source.md
This document provides the steps you need to take to update the reference assembly when adding new **public** APIs to an implementation assembly (post [API Review](adding-api-guidelines.md)). ## For most assemblies within libraries 1. Implement the API in the source assembly and [build it](../workflow/building/libraries/README.md#building-individual-libraries). Note that when adding new public types, this might fail with a `TypeMustExist` error. The deadlock can be worked around by disabling the `RunApiCompat` property: `dotnet build /p:RunApiCompat=false`. 2. Run the following command (from the src directory) `dotnet msbuild /t:GenerateReferenceAssemblySource` to update the reference assembly**. 3. Navigate to the ref directory and build the reference assembly. 4. Add, build, and run tests. ** **Note:** If you already added the new API to the reference source, re-generating it (after building the source assembly) will update it to be fully qualified and placed in the correct order. This can be done by running the `GenerateReferenceAssemblySource` command from the ref directory. ## For System.Runtime These steps can also be applied to some unique assemblies which depend on changes in System.Private.Corelib. (partial facades like System.Memory, for example). 1) Run `dotnet build --no-incremental /t:GenerateReferenceSource` from the System.Runtime/src directory. 2) Filter out all unrelated changes and extract the changes you care about (ignore certain attributes being removed). Generally, this step is not required for other reference assemblies. ## For Full Facade Assemblies implementation assemblies For implementation assemblies that are "full facades" over another assembly but define types in the reference assembly (ex. System.Runtime.Serialization.Json or System.Xml.XDocument), use the following command to generate the reference source code instead: ``` dotnet msbuild /t:GenerateReferenceAssemblySource /p:GenAPIAdditionalParameters=--follow-type-forwards ``` ## For .NETFramework Facade Assemblies Some assemblies define types in .NETStandard and .NETCore but require facades on .NETFramework to forward types to their existing location in .NETFramework. In these cases we need to add type forwards manually to the .NETFramework build of the reference assembly. TypeForwards must be added for every type in the compatible .NETStandard reference assembly that exists in the .NETFramework, types which are defined in the .NETFramework reference should be factored into a shared source file.
This document provides the steps you need to take to update the reference assembly when adding new **public** APIs to an implementation assembly (post [API Review](adding-api-guidelines.md)). ## For most assemblies within libraries 1. Implement the API in the source assembly and [build it](../workflow/building/libraries/README.md#building-individual-libraries). Note that when adding new public types, this might fail with a `TypeMustExist` error. The deadlock can be worked around by disabling the `RunApiCompat` property: `dotnet build /p:RunApiCompat=false`. 2. Run the following command (from the src directory) `dotnet msbuild /t:GenerateReferenceAssemblySource` to update the reference assembly**. 3. Navigate to the ref directory and build the reference assembly. 4. Add, build, and run tests. ** **Note:** If you already added the new API to the reference source, re-generating it (after building the source assembly) will update it to be fully qualified and placed in the correct order. This can be done by running the `GenerateReferenceAssemblySource` command from the ref directory. ## For System.Runtime These steps can also be applied to some unique assemblies which depend on changes in System.Private.Corelib. (partial facades like System.Memory, for example). 1) Run `dotnet build --no-incremental /t:GenerateReferenceSource` from the System.Runtime/src directory. 2) Filter out all unrelated changes and extract the changes you care about (ignore certain attributes being removed). Generally, this step is not required for other reference assemblies. ## For Full Facade Assemblies implementation assemblies For implementation assemblies that are "full facades" over another assembly but define types in the reference assembly (ex. System.Runtime.Serialization.Json or System.Xml.XDocument), use the following command to generate the reference source code instead: ``` dotnet msbuild /t:GenerateReferenceAssemblySource /p:GenAPIAdditionalParameters=--follow-type-forwards ``` ## For .NETFramework Facade Assemblies Some assemblies define types in .NETStandard and .NETCore but require facades on .NETFramework to forward types to their existing location in .NETFramework. In these cases we need to add type forwards manually to the .NETFramework build of the reference assembly. TypeForwards must be added for every type in the compatible .NETStandard reference assembly that exists in the .NETFramework, types which are defined in the .NETFramework reference should be factored into a shared source file.
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/debugger/tests/debugger-test/other.js
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. "use strict"; function big_array_js_test (len) { const big = new Array(len); for (let i=0; i < len; i ++) { big[i]=i + 1000; } console.log('break here'); }; function object_js_test () { const obj = { a_obj: { aa: 5, ab: 'foo' }, b_arr: [ 10, 12 ] }; return obj; }; function getters_js_test () { const ptd = { get Int () { return 5; }, get String () { return "foobar"; }, get DT () { return "dt"; }, get IntArray () { return [1,2,3]; }, get DTArray () { return ["dt0", "dt1"]; }, DTAutoProperty: "dt", StringField: "string field value" }; console.log (`break here`); return ptd; } function exception_caught_test () { try { throw new TypeError ('exception caught'); } catch (e) { console.log(e); } } function exception_uncaught_test () { console.log('uncaught test'); throw new RangeError ('exception uncaught'); } function exceptions_test () { exception_caught_test (); exception_uncaught_test (); } function negative_cfo_test (str_value = null) { const ptd = { get Int () { return 5; }, get String () { return "foobar"; }, get DT () { return "dt"; }, get IntArray () { return [1,2,3]; }, get DTArray () { return ["dt0", "dt1"]; }, DTAutoProperty: "dt", StringField: str_value }; console.log (`break here`); return ptd; } function eval_call_on_frame_test () { let obj = { a: 5, b: "hello", c: { c_x: 1 }, }; let obj_undefined = undefined; console.log(`break here`); } function get_properties_test () { let vehicle = { kind: "car", make: "mini", get available () { return true; } }; let obj = { owner_name: "foo", get owner_last_name () { return "bar"; }, } // obj.prototype.this_vehicle = vehicle; Object.setPrototypeOf(obj, vehicle); console.log(`break here`); } function malloc_to_reallocate_test () { //need to allocate this buffer size to force wasm linear memory to grow const _debugger_buffer = Module._malloc(4500000); Module._free(_debugger_buffer); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. "use strict"; function big_array_js_test (len) { const big = new Array(len); for (let i=0; i < len; i ++) { big[i]=i + 1000; } console.log('break here'); }; function object_js_test () { const obj = { a_obj: { aa: 5, ab: 'foo' }, b_arr: [ 10, 12 ] }; return obj; }; function getters_js_test () { const ptd = { get Int () { return 5; }, get String () { return "foobar"; }, get DT () { return "dt"; }, get IntArray () { return [1,2,3]; }, get DTArray () { return ["dt0", "dt1"]; }, DTAutoProperty: "dt", StringField: "string field value" }; console.log (`break here`); return ptd; } function exception_caught_test () { try { throw new TypeError ('exception caught'); } catch (e) { console.log(e); } } function exception_uncaught_test () { console.log('uncaught test'); throw new RangeError ('exception uncaught'); } function exceptions_test () { exception_caught_test (); exception_uncaught_test (); } function negative_cfo_test (str_value = null) { const ptd = { get Int () { return 5; }, get String () { return "foobar"; }, get DT () { return "dt"; }, get IntArray () { return [1,2,3]; }, get DTArray () { return ["dt0", "dt1"]; }, DTAutoProperty: "dt", StringField: str_value }; console.log (`break here`); return ptd; } function eval_call_on_frame_test () { let obj = { a: 5, b: "hello", c: { c_x: 1 }, }; let obj_undefined = undefined; console.log(`break here`); } function get_properties_test () { let vehicle = { kind: "car", make: "mini", get available () { return true; } }; let obj = { owner_name: "foo", get owner_last_name () { return "bar"; }, } // obj.prototype.this_vehicle = vehicle; Object.setPrototypeOf(obj, vehicle); console.log(`break here`); } function malloc_to_reallocate_test () { //need to allocate this buffer size to force wasm linear memory to grow const _debugger_buffer = Module._malloc(4500000); Module._free(_debugger_buffer); }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/sample/wasm/Directory.Build.targets
<Project> <Import Project="../Directory.Build.targets" /> <Import Project="$(MonoProjectRoot)\wasm\build\WasmApp.InTree.targets" /> <PropertyGroup> <RunScriptInputName Condition="'$(TargetOS)' == 'Browser' and '$(OS)' != 'Windows_NT'">WasmRunnerTemplate.sh</RunScriptInputName> <RunScriptInputName Condition="'$(TargetOS)' == 'Browser' and '$(OS)' == 'Windows_NT'">WasmRunnerTemplate.cmd</RunScriptInputName> <RunScriptOutputPath>$([MSBuild]::NormalizePath('$(WasmAppDir)', '$(RunScriptOutputName)'))</RunScriptOutputPath> </PropertyGroup> <Target Name="BuildSampleInTree" Inputs=" Program.cs; $(_WasmMainJSFileName); " Outputs=" bin/$(Configuration)/AppBundle/dotnet.wasm; bin/$(Configuration)/AppBundle/$(_WasmMainJSFileName); "> <Error Condition="'$(WasmMainJSPath)' == ''" Text="%24(WasmMainJSPath) property needs to be set" /> <PropertyGroup> <_ScriptExt Condition="'$(OS)' == 'Windows_NT'">.cmd</_ScriptExt> <_ScriptExt Condition="'$(OS)' != 'Windows_NT'">.sh</_ScriptExt> <_Dotnet>$(RepoRoot)dotnet$(_ScriptExt)</_Dotnet> <_AOTFlag Condition="'$(RunAOTCompilation)' != ''">/p:RunAOTCompilation=$(RunAOTCompilation)</_AOTFlag> <_WasmMainJSFileName>$([System.IO.Path]::GetFileName('$(WasmMainJSPath)'))</_WasmMainJSFileName> </PropertyGroup> <Exec Command="$(_Dotnet) publish -bl /p:Configuration=$(Configuration) /p:TargetArchitecture=wasm /p:TargetOS=Browser $(_AOTFlag) $(_SampleProject)" /> </Target> <Target Name="RunSampleWithV8" DependsOnTargets="BuildSampleInTree"> <Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="v8 --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args)" IgnoreExitCode="true" /> </Target> <Target Name="RunSampleWithNode" DependsOnTargets="BuildSampleInTree"> <Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="node --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args)" IgnoreExitCode="true" /> </Target> <Target Name="CheckServe"> <Exec Command="dotnet tool install -g dotnet-serve" IgnoreExitCode="true" /> </Target> <Target Name="RunSampleWithBrowser" DependsOnTargets="BuildSampleInTree;CheckServe"> <Exec Command="$(_Dotnet) serve -o -d:bin/$(Configuration)/AppBundle -p:8000 --mime .mjs=text/javascript" IgnoreExitCode="true" YieldDuringToolExecution="true" /> </Target> <Target Name="RunSampleWithBrowserAndSimpleServer" DependsOnTargets="BuildSampleInTree"> <Exec Command="$(_Dotnet) build -c $(Configuration) ..\simple-server\HttpServer.csproj" /> <Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="..\..\..\..\simple-server\bin\$(Configuration)\net6.0\HttpServer" /> </Target> <Target Name="TriggerGenerateRunScript" Condition="'$(GenerateRunScriptForSample)' == 'true'" BeforeTargets="CopyAppZipToHelixTestDir" DependsOnTargets="GenerateRunScriptForRunningSampleOnHelix" /> </Project>
<Project> <Import Project="../Directory.Build.targets" /> <Import Project="$(MonoProjectRoot)\wasm\build\WasmApp.InTree.targets" /> <PropertyGroup> <RunScriptInputName Condition="'$(TargetOS)' == 'Browser' and '$(OS)' != 'Windows_NT'">WasmRunnerTemplate.sh</RunScriptInputName> <RunScriptInputName Condition="'$(TargetOS)' == 'Browser' and '$(OS)' == 'Windows_NT'">WasmRunnerTemplate.cmd</RunScriptInputName> <RunScriptOutputPath>$([MSBuild]::NormalizePath('$(WasmAppDir)', '$(RunScriptOutputName)'))</RunScriptOutputPath> </PropertyGroup> <Target Name="BuildSampleInTree" Inputs=" Program.cs; $(_WasmMainJSFileName); " Outputs=" bin/$(Configuration)/AppBundle/dotnet.wasm; bin/$(Configuration)/AppBundle/$(_WasmMainJSFileName); "> <Error Condition="'$(WasmMainJSPath)' == ''" Text="%24(WasmMainJSPath) property needs to be set" /> <PropertyGroup> <_ScriptExt Condition="'$(OS)' == 'Windows_NT'">.cmd</_ScriptExt> <_ScriptExt Condition="'$(OS)' != 'Windows_NT'">.sh</_ScriptExt> <_Dotnet>$(RepoRoot)dotnet$(_ScriptExt)</_Dotnet> <_AOTFlag Condition="'$(RunAOTCompilation)' != ''">/p:RunAOTCompilation=$(RunAOTCompilation)</_AOTFlag> <_WasmMainJSFileName>$([System.IO.Path]::GetFileName('$(WasmMainJSPath)'))</_WasmMainJSFileName> </PropertyGroup> <Exec Command="$(_Dotnet) publish -bl /p:Configuration=$(Configuration) /p:TargetArchitecture=wasm /p:TargetOS=Browser $(_AOTFlag) $(_SampleProject)" /> </Target> <Target Name="RunSampleWithV8" DependsOnTargets="BuildSampleInTree"> <Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="v8 --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args)" IgnoreExitCode="true" /> </Target> <Target Name="RunSampleWithNode" DependsOnTargets="BuildSampleInTree"> <Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="node --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args)" IgnoreExitCode="true" /> </Target> <Target Name="CheckServe"> <Exec Command="dotnet tool install -g dotnet-serve" IgnoreExitCode="true" /> </Target> <Target Name="RunSampleWithBrowser" DependsOnTargets="BuildSampleInTree;CheckServe"> <Exec Command="$(_Dotnet) serve -o -d:bin/$(Configuration)/AppBundle -p:8000 --mime .mjs=text/javascript" IgnoreExitCode="true" YieldDuringToolExecution="true" /> </Target> <Target Name="RunSampleWithBrowserAndSimpleServer" DependsOnTargets="BuildSampleInTree"> <Exec Command="$(_Dotnet) build -c $(Configuration) ..\simple-server\HttpServer.csproj" /> <Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="..\..\..\..\simple-server\bin\$(Configuration)\net6.0\HttpServer" /> </Target> <Target Name="TriggerGenerateRunScript" Condition="'$(GenerateRunScriptForSample)' == 'true'" BeforeTargets="CopyAppZipToHelixTestDir" DependsOnTargets="GenerateRunScriptForRunningSampleOnHelix" /> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/runtime/cjs/dotnet.cjs.pre.js
const MONO = {}, BINDING = {}, INTERNAL = {}; if (ENVIRONMENT_IS_GLOBAL) { if (globalThis.Module.ready) { throw new Error("MONO_WASM: Module.ready couldn't be redefined.") } globalThis.Module.ready = Module.ready; Module = createDotnetRuntime = globalThis.Module; } else if (typeof createDotnetRuntime === "object") { Module = { ready: Module.ready, __undefinedConfig: Object.keys(createDotnetRuntime).length === 1 }; Object.assign(Module, createDotnetRuntime); createDotnetRuntime = Module; } else if (typeof createDotnetRuntime === "function") { Module = { ready: Module.ready }; const extension = createDotnetRuntime({ MONO, BINDING, INTERNAL, Module }) if (extension.ready) { throw new Error("MONO_WASM: Module.ready couldn't be redefined.") } Object.assign(Module, extension); createDotnetRuntime = Module; } else { throw new Error("MONO_WASM: Can't locate global Module object or moduleFactory callback of createDotnetRuntime function.") }
const MONO = {}, BINDING = {}, INTERNAL = {}; if (ENVIRONMENT_IS_GLOBAL) { if (globalThis.Module.ready) { throw new Error("MONO_WASM: Module.ready couldn't be redefined.") } globalThis.Module.ready = Module.ready; Module = createDotnetRuntime = globalThis.Module; } else if (typeof createDotnetRuntime === "object") { Module = { ready: Module.ready, __undefinedConfig: Object.keys(createDotnetRuntime).length === 1 }; Object.assign(Module, createDotnetRuntime); createDotnetRuntime = Module; } else if (typeof createDotnetRuntime === "function") { Module = { ready: Module.ready }; const extension = createDotnetRuntime({ MONO, BINDING, INTERNAL, Module }) if (extension.ready) { throw new Error("MONO_WASM: Module.ready couldn't be redefined.") } Object.assign(Module, extension); createDotnetRuntime = Module; } else { throw new Error("MONO_WASM: Can't locate global Module object or moduleFactory callback of createDotnetRuntime function.") }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/BuildWasmApps/Wasm.Build.Tests/data/Workloads.Directory.Build.targets
<Project> <PropertyGroup> <_MicrosoftNetCoreAppRefDir>$(AppRefDir)\</_MicrosoftNetCoreAppRefDir> </PropertyGroup> <ItemGroup> <EmscriptenEnvVars Include="FROZEN_CACHE=" Condition="'$(OS)' == 'Windows_NT'" /> </ItemGroup> <Target Name="PrintRuntimePackPath" BeforeTargets="Publish"> <Message Text="** MicrosoftNetCoreAppRuntimePackDir : %(ResolvedRuntimePack.PackageDirectory)" Importance="High" /> </Target> <!-- Add the resolved targeting pack to the assembly search path. --> <!-- <Target Name="UseTargetingPackForAssemblySearchPaths" BeforeTargets="ResolveAssemblyReferences; DesignTimeResolveAssemblyReferences" Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <PropertyGroup> <AssemblySearchPaths>$(AssemblySearchPaths);$(MicrosoftNetCoreAppRefPackRefDir.TrimEnd('/\'))</AssemblySearchPaths> <DesignTimeAssemblySearchPaths>$(DesignTimeAssemblySearchPaths);$(MicrosoftNetCoreAppRefPackRefDir.TrimEnd('/\'))</DesignTimeAssemblySearchPaths> </PropertyGroup> </Target> --> <!-- SDK tries to download runtime packs when RuntimeIdentifier is set, remove them from PackageDownload item. --> <Target Name="RemoveRuntimePackFromDownloadItem" AfterTargets="ProcessFrameworkReferences"> <ItemGroup> <PackageDownload Remove="@(PackageDownload)" Condition="'$(UsePackageDownload)' == 'true' and $([System.String]::Copy('%(Identity)').StartsWith('Microsoft.NETCore.App.Runtime'))" /> <PackageReference Remove="@(PackageReference)" Condition="'$(UsePackageDownload)' != 'true' and $([System.String]::Copy('%(Identity)').StartsWith('Microsoft.NETCore.App.Runtime'))" /> </ItemGroup> </Target> <!-- Use local targeting pack for NetCoreAppCurrent. --> <Target Name="UpdateTargetingAndRuntimePack" AfterTargets="ResolveFrameworkReferences"> <ItemGroup> <ResolvedTargetingPack Path="$(_MicrosoftNetCoreAppRefDir.TrimEnd('/\'))" NuGetPackageVersion="$(RuntimePackInWorkloadVersion)" PackageDirectory="$(_MicrosoftNetCoreAppRefDir.TrimEnd('/\'))" Condition="'%(ResolvedTargetingPack.RuntimeFrameworkName)' == 'Microsoft.NETCore.App' and Exists('$(_MicrosoftNetCoreAppRefDir)data\FrameworkList.xml')" /> <ResolvedRuntimePack Update="Microsoft.NETCore.App.Runtime.Mono.browser-wasm" FrameworkName="Microsoft.NETCore.App" NuGetPackageId="Microsoft.NETCore.App.Runtime.Mono.browser-wasm" NuGetPackageVersion="$(RuntimePackInWorkloadVersion)" PackageDirectory="$(NetCoreTargetingPackRoot)\Microsoft.NETCore.App.Runtime.Mono.browser-wasm\$(RuntimePackInWorkloadVersion)" RuntimeIdentifier="browser-wasm" /> <ResolvedFrameworkReference Update="Microsoft.NETCore.App" TargetingPackPath="$(_MicrosoftNetCoreAppRefDir.TrimEnd('/\'))" RuntimePackName="Microsoft.NETCore.App.Runtime.Mono.browser-wasm" RuntimePackVersion="$(RuntimePackInWorkloadVersion)" RuntimePackPath="$(NetCoreTargetingPackRoot)\Microsoft.NETCore.App.Runtime.Mono.browser-wasm\$(RuntimePackInWorkloadVersion)" RuntimeIdentifier="browser-wasm" /> </ItemGroup> </Target> <!-- Update the local targeting pack's version as it's written into the runtimeconfig.json file to select the right framework. --> <Target Name="UpdateRuntimeFrameworkVersion" AfterTargets="ResolveTargetingPackAssets"> <ItemGroup> <RuntimeFramework Version="$(RuntimePackInWorkloadVersion)" Condition="'%(RuntimeFramework.FrameworkName)' == 'Microsoft.NETCore.App'" /> </ItemGroup> </Target> <!-- Filter out conflicting implicit assembly references. --> <Target Name="FilterImplicitAssemblyReferences" DependsOnTargets="ResolveProjectReferences" AfterTargets="ResolveTargetingPackAssets"> <ItemGroup> <_targetingPackReferenceExclusion Include="$(TargetName)" /> <_targetingPackReferenceExclusion Include="@(_ResolvedProjectReferencePaths->'%(Filename)')" /> <_targetingPackReferenceExclusion Include="@(DefaultReferenceExclusion)" /> </ItemGroup> <ItemGroup> <_targetingPackReferenceWithExclusion Include="@(Reference)"> <Exclusion>%(_targetingPackReferenceExclusion.Identity)</Exclusion> </_targetingPackReferenceWithExclusion> <Reference Remove="@(_targetingPackReferenceWithExclusion)" Condition="'%(_targetingPackReferenceWithExclusion.ExternallyResolved)' == 'true' and '%(_targetingPackReferenceWithExclusion.Filename)' == '%(_targetingPackReferenceWithExclusion.Exclusion)'" /> </ItemGroup> </Target> </Project>
<Project> <PropertyGroup> <_MicrosoftNetCoreAppRefDir>$(AppRefDir)\</_MicrosoftNetCoreAppRefDir> </PropertyGroup> <ItemGroup> <EmscriptenEnvVars Include="FROZEN_CACHE=" Condition="'$(OS)' == 'Windows_NT'" /> </ItemGroup> <Target Name="PrintRuntimePackPath" BeforeTargets="Publish"> <Message Text="** MicrosoftNetCoreAppRuntimePackDir : %(ResolvedRuntimePack.PackageDirectory)" Importance="High" /> </Target> <!-- Add the resolved targeting pack to the assembly search path. --> <!-- <Target Name="UseTargetingPackForAssemblySearchPaths" BeforeTargets="ResolveAssemblyReferences; DesignTimeResolveAssemblyReferences" Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <PropertyGroup> <AssemblySearchPaths>$(AssemblySearchPaths);$(MicrosoftNetCoreAppRefPackRefDir.TrimEnd('/\'))</AssemblySearchPaths> <DesignTimeAssemblySearchPaths>$(DesignTimeAssemblySearchPaths);$(MicrosoftNetCoreAppRefPackRefDir.TrimEnd('/\'))</DesignTimeAssemblySearchPaths> </PropertyGroup> </Target> --> <!-- SDK tries to download runtime packs when RuntimeIdentifier is set, remove them from PackageDownload item. --> <Target Name="RemoveRuntimePackFromDownloadItem" AfterTargets="ProcessFrameworkReferences"> <ItemGroup> <PackageDownload Remove="@(PackageDownload)" Condition="'$(UsePackageDownload)' == 'true' and $([System.String]::Copy('%(Identity)').StartsWith('Microsoft.NETCore.App.Runtime'))" /> <PackageReference Remove="@(PackageReference)" Condition="'$(UsePackageDownload)' != 'true' and $([System.String]::Copy('%(Identity)').StartsWith('Microsoft.NETCore.App.Runtime'))" /> </ItemGroup> </Target> <!-- Use local targeting pack for NetCoreAppCurrent. --> <Target Name="UpdateTargetingAndRuntimePack" AfterTargets="ResolveFrameworkReferences"> <ItemGroup> <ResolvedTargetingPack Path="$(_MicrosoftNetCoreAppRefDir.TrimEnd('/\'))" NuGetPackageVersion="$(RuntimePackInWorkloadVersion)" PackageDirectory="$(_MicrosoftNetCoreAppRefDir.TrimEnd('/\'))" Condition="'%(ResolvedTargetingPack.RuntimeFrameworkName)' == 'Microsoft.NETCore.App' and Exists('$(_MicrosoftNetCoreAppRefDir)data\FrameworkList.xml')" /> <ResolvedRuntimePack Update="Microsoft.NETCore.App.Runtime.Mono.browser-wasm" FrameworkName="Microsoft.NETCore.App" NuGetPackageId="Microsoft.NETCore.App.Runtime.Mono.browser-wasm" NuGetPackageVersion="$(RuntimePackInWorkloadVersion)" PackageDirectory="$(NetCoreTargetingPackRoot)\Microsoft.NETCore.App.Runtime.Mono.browser-wasm\$(RuntimePackInWorkloadVersion)" RuntimeIdentifier="browser-wasm" /> <ResolvedFrameworkReference Update="Microsoft.NETCore.App" TargetingPackPath="$(_MicrosoftNetCoreAppRefDir.TrimEnd('/\'))" RuntimePackName="Microsoft.NETCore.App.Runtime.Mono.browser-wasm" RuntimePackVersion="$(RuntimePackInWorkloadVersion)" RuntimePackPath="$(NetCoreTargetingPackRoot)\Microsoft.NETCore.App.Runtime.Mono.browser-wasm\$(RuntimePackInWorkloadVersion)" RuntimeIdentifier="browser-wasm" /> </ItemGroup> </Target> <!-- Update the local targeting pack's version as it's written into the runtimeconfig.json file to select the right framework. --> <Target Name="UpdateRuntimeFrameworkVersion" AfterTargets="ResolveTargetingPackAssets"> <ItemGroup> <RuntimeFramework Version="$(RuntimePackInWorkloadVersion)" Condition="'%(RuntimeFramework.FrameworkName)' == 'Microsoft.NETCore.App'" /> </ItemGroup> </Target> <!-- Filter out conflicting implicit assembly references. --> <Target Name="FilterImplicitAssemblyReferences" DependsOnTargets="ResolveProjectReferences" AfterTargets="ResolveTargetingPackAssets"> <ItemGroup> <_targetingPackReferenceExclusion Include="$(TargetName)" /> <_targetingPackReferenceExclusion Include="@(_ResolvedProjectReferencePaths->'%(Filename)')" /> <_targetingPackReferenceExclusion Include="@(DefaultReferenceExclusion)" /> </ItemGroup> <ItemGroup> <_targetingPackReferenceWithExclusion Include="@(Reference)"> <Exclusion>%(_targetingPackReferenceExclusion.Identity)</Exclusion> </_targetingPackReferenceWithExclusion> <Reference Remove="@(_targetingPackReferenceWithExclusion)" Condition="'%(_targetingPackReferenceWithExclusion.ExternallyResolved)' == 'true' and '%(_targetingPackReferenceWithExclusion.Filename)' == '%(_targetingPackReferenceWithExclusion.Exclusion)'" /> </ItemGroup> </Target> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Net.Security/tests/EnterpriseTests/README.md
# Enterprise Scenario Testing Detailed instructions for running these tests is located here: src\libraries\Common\tests\System\Net\EnterpriseTests\setup\README.md
# Enterprise Scenario Testing Detailed instructions for running these tests is located here: src\libraries\Common\tests\System\Net\EnterpriseTests\setup\README.md
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Diagnostics.DiagnosticSource/src/HttpCorrelationProtocol.md
# Note Starting with System.Diagnostics.DiagnosticSource 4.6.0 (that ships with .Net Core 3.0), we are moving towards [W3C Trace-Context](https://www.w3.org/TR/trace-context/) standard. We still support Request-Id ([hierarchical](HierarchicalRequestId.md) version) and it is still the default format for `System.Diagnostics.Activity`. [Flat Request-Id](FlatRequestId.md) is **deprecated**. # Overview One of the common problems in microservices development is ability to trace request flow from client (application, browser) through all the services involved in processing. Typical scenarios include: 1. Tracing error received by user 2. Performance analysis and optimization: whole stack of request needs to be analyzed to find where performance issues come from 3. A/B testing: metrics for requests with experimental features should be distinguished and compared to 'production' data. These scenarios require every request to carry additional context and services to enrich their telemetry events with this context, so it would possible to correlate telemetry from all services involved in operation processing. Tracing an operation involves an overhead on application performance and should always be considered as optional, so application may not trace anything, trace only particular operations or some percent of all operations. Tracing should be consistent: operation should be either fully traced, or not traced at all. This document provides guidance on the context needed for telemetry correlation and describes its format in HTTP communication. The context is not specific to HTTP protocol, it represents set of identifiers that is needed or helpful for end-to-end tracing. Applications widely use distributed queues for asynchronous processing so operation may start (or continue) from a queue message; applications should propagate the context through the queues and restore (create) it when they start processing received task. # HTTP Protocol proposal | Header name | Format | Description | | ----------------------| ---------- | ---------- | | Request-Id | Required. String | Unique identifier for every HTTP request involved in operation processing | | Correlation-Context | Optional. Comma separated list of key-value pairs: Id=id, key1=value1, key2=value2 | Operation context which is propagated across all services involved in operation processing | ## Request-Id `Request-Id` uniquely identifies every HTTP request involved in operation processing. Request-Id is generated on the caller side and passed to callee. Implementation of this protocol should expect to receive `Request-Id` in header of incoming request. Absence of Request-Id indicates that it is either the first instrumented service in the system or this request was not traced by upstream service and therefore does not have any context associated with it. To start tracing the request, implementation MUST generate new `Request-Id` (see [Root Request Id Generation](#root-request-id-generation)) for the incoming request. When Request-Id is provided by upstream service, there is no guarantee that it is unique within the entire system. Implementation SHOULD make it unique by adding small suffix to incoming Request-Id to represent internal activity and use it for outgoing requests, see more details in [Hierarchical Request-Id document](HierarchicalRequestId.md). `Request-Id` is required field, i.e., every instrumented request MUST have it. If implementation does not find `Request-Id` in the incoming request headers, it should consider it as non-traced and MAY not look for `Correlation-Context`. It is essential that 'incoming' and 'outgoing' Request-Ids are included in the telemetry events, so implementation of this protocol MUST provide read access to Request-Id for logging systems. ### Request-Id Format `Request-Id` is a string up to 1024 bytes length. It contains only [Base64](https://en.wikipedia.org/wiki/Base64) and "-" (hyphen), "|" (vertical bar), "." (dot), and "_" (underscore) characters. Vertical bar, dot and underscore are reserved characters that are used to mark and delimit hierarchical Request-Id, and must not be present in the nodes. Hyphen may be used in the nodes. Implementations SHOULD support hierarchical structure for the Request-Id, described in [Hierarchical Request-Id document](HierarchicalRequestId.md). See [Flat Request-Id](FlatRequestId.md) for non-hierarchical Request-Id requirements. ## Correlation-Context First service MAY add state (key value pairs) that will automatically propagate to all other services including intermediary services (that support this protocol). A typical scenarios for the Correlation-Context include logging control and sampling or A/B testing (feature flags) so that the first service has a way to pass this kind of information down to all services (including intermediary). All services other than the first one SHOULD consider Correlation-Context as read-only. It is important to keep the size of any property small because these get serialized into HTTP headers which have significant size restrictions; Correlation-Context parsing, storing and propagation involves performance overhead on all downstream services. Correlation-Context MUST NOT be used as generic data passing mechanism between services or within one service. We anticipate that there will be common well-known Correlation-Context keys. If you wish to use this for you own custom (not well-known) context key, prefix it with "@". `Correlation-Context` is optional, it may or may not be provided by upstream (instrumented) service. If `Correlation-Context` is provided by upstream service, implementation MUST propagate it further to downstream services. It MUST NOT change or remove properties and SHOULD NOT add new properties. Implementation MUST provide read access to `Correlation-Context` for logging systems and MUST support adding properties to Correlation-Context. ### Correlation-Context Format `Correlation-Context` is represented as comma separated list of key value pairs, where each pair is represented in key=value format: `Correlation-Context: key1=value1, key2=value2` Keys and values MUST NOT contain "=" (equals) or "," (comma) characters. Overall Correlation-Context length MUST NOT exceed 1024 bytes, key and value length should stay well under the combined limit of 1024 bytes. Note that uniqueness of the key within the Correlation-Context is not guaranteed. Context received from upstream service is read-only and implementation MUST NOT remove or aggregate duplicated keys. # HTTP Guidelines and Limitations - [HTTP 1.1 RFC2616](https://tools.ietf.org/html/rfc2616) - [HTTP Header encoding RFC5987](https://tools.ietf.org/html/rfc5987) - De-facto overall HTTP headers size is limited to several kilobytes (depending on a web server) # Industry standards - [Google Dapper tracing system](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36356.pdf) - [Zipkin](http://zipkin.io/) - [OpenTracing](http://opentracing.io/) # See also - [Hierarchical Request-Id](HierarchicalRequestId.md) - [Flat Request-Id](FlatRequestId.md)
# Note Starting with System.Diagnostics.DiagnosticSource 4.6.0 (that ships with .Net Core 3.0), we are moving towards [W3C Trace-Context](https://www.w3.org/TR/trace-context/) standard. We still support Request-Id ([hierarchical](HierarchicalRequestId.md) version) and it is still the default format for `System.Diagnostics.Activity`. [Flat Request-Id](FlatRequestId.md) is **deprecated**. # Overview One of the common problems in microservices development is ability to trace request flow from client (application, browser) through all the services involved in processing. Typical scenarios include: 1. Tracing error received by user 2. Performance analysis and optimization: whole stack of request needs to be analyzed to find where performance issues come from 3. A/B testing: metrics for requests with experimental features should be distinguished and compared to 'production' data. These scenarios require every request to carry additional context and services to enrich their telemetry events with this context, so it would possible to correlate telemetry from all services involved in operation processing. Tracing an operation involves an overhead on application performance and should always be considered as optional, so application may not trace anything, trace only particular operations or some percent of all operations. Tracing should be consistent: operation should be either fully traced, or not traced at all. This document provides guidance on the context needed for telemetry correlation and describes its format in HTTP communication. The context is not specific to HTTP protocol, it represents set of identifiers that is needed or helpful for end-to-end tracing. Applications widely use distributed queues for asynchronous processing so operation may start (or continue) from a queue message; applications should propagate the context through the queues and restore (create) it when they start processing received task. # HTTP Protocol proposal | Header name | Format | Description | | ----------------------| ---------- | ---------- | | Request-Id | Required. String | Unique identifier for every HTTP request involved in operation processing | | Correlation-Context | Optional. Comma separated list of key-value pairs: Id=id, key1=value1, key2=value2 | Operation context which is propagated across all services involved in operation processing | ## Request-Id `Request-Id` uniquely identifies every HTTP request involved in operation processing. Request-Id is generated on the caller side and passed to callee. Implementation of this protocol should expect to receive `Request-Id` in header of incoming request. Absence of Request-Id indicates that it is either the first instrumented service in the system or this request was not traced by upstream service and therefore does not have any context associated with it. To start tracing the request, implementation MUST generate new `Request-Id` (see [Root Request Id Generation](#root-request-id-generation)) for the incoming request. When Request-Id is provided by upstream service, there is no guarantee that it is unique within the entire system. Implementation SHOULD make it unique by adding small suffix to incoming Request-Id to represent internal activity and use it for outgoing requests, see more details in [Hierarchical Request-Id document](HierarchicalRequestId.md). `Request-Id` is required field, i.e., every instrumented request MUST have it. If implementation does not find `Request-Id` in the incoming request headers, it should consider it as non-traced and MAY not look for `Correlation-Context`. It is essential that 'incoming' and 'outgoing' Request-Ids are included in the telemetry events, so implementation of this protocol MUST provide read access to Request-Id for logging systems. ### Request-Id Format `Request-Id` is a string up to 1024 bytes length. It contains only [Base64](https://en.wikipedia.org/wiki/Base64) and "-" (hyphen), "|" (vertical bar), "." (dot), and "_" (underscore) characters. Vertical bar, dot and underscore are reserved characters that are used to mark and delimit hierarchical Request-Id, and must not be present in the nodes. Hyphen may be used in the nodes. Implementations SHOULD support hierarchical structure for the Request-Id, described in [Hierarchical Request-Id document](HierarchicalRequestId.md). See [Flat Request-Id](FlatRequestId.md) for non-hierarchical Request-Id requirements. ## Correlation-Context First service MAY add state (key value pairs) that will automatically propagate to all other services including intermediary services (that support this protocol). A typical scenarios for the Correlation-Context include logging control and sampling or A/B testing (feature flags) so that the first service has a way to pass this kind of information down to all services (including intermediary). All services other than the first one SHOULD consider Correlation-Context as read-only. It is important to keep the size of any property small because these get serialized into HTTP headers which have significant size restrictions; Correlation-Context parsing, storing and propagation involves performance overhead on all downstream services. Correlation-Context MUST NOT be used as generic data passing mechanism between services or within one service. We anticipate that there will be common well-known Correlation-Context keys. If you wish to use this for you own custom (not well-known) context key, prefix it with "@". `Correlation-Context` is optional, it may or may not be provided by upstream (instrumented) service. If `Correlation-Context` is provided by upstream service, implementation MUST propagate it further to downstream services. It MUST NOT change or remove properties and SHOULD NOT add new properties. Implementation MUST provide read access to `Correlation-Context` for logging systems and MUST support adding properties to Correlation-Context. ### Correlation-Context Format `Correlation-Context` is represented as comma separated list of key value pairs, where each pair is represented in key=value format: `Correlation-Context: key1=value1, key2=value2` Keys and values MUST NOT contain "=" (equals) or "," (comma) characters. Overall Correlation-Context length MUST NOT exceed 1024 bytes, key and value length should stay well under the combined limit of 1024 bytes. Note that uniqueness of the key within the Correlation-Context is not guaranteed. Context received from upstream service is read-only and implementation MUST NOT remove or aggregate duplicated keys. # HTTP Guidelines and Limitations - [HTTP 1.1 RFC2616](https://tools.ietf.org/html/rfc2616) - [HTTP Header encoding RFC5987](https://tools.ietf.org/html/rfc5987) - De-facto overall HTTP headers size is limited to several kilobytes (depending on a web server) # Industry standards - [Google Dapper tracing system](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36356.pdf) - [Zipkin](http://zipkin.io/) - [OpenTracing](http://opentracing.io/) # See also - [Hierarchical Request-Id](HierarchicalRequestId.md) - [Flat Request-Id](FlatRequestId.md)
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/Directory.Build.props
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props, $(MSBuildThisFileDirectory)..))" /> <PropertyGroup> <EnableDefaultItems>true</EnableDefaultItems> </PropertyGroup> </Project>
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props, $(MSBuildThisFileDirectory)..))" /> <PropertyGroup> <EnableDefaultItems>true</EnableDefaultItems> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/Interop/ObjectiveC/ObjectiveCMarshalAPI/Directory.Build.props
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="../../Directory.Build.props" /> <!-- Properties for all ObjectiveC managed test assets --> <PropertyGroup> </PropertyGroup> </Project>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="../../Directory.Build.props" /> <!-- Properties for all ObjectiveC managed test assets --> <PropertyGroup> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/installer/pkg/sfx/installers/dotnet-runtime-deps/dotnet-runtime-deps-opensuse.42.proj
<Project Sdk="Microsoft.Build.NoTargets"> <PropertyGroup> <GenerateInstallers Condition="'$(BuildRpmPackage)' != 'true'">false</GenerateInstallers> <PackageTargetOS>opensuse.42</PackageTargetOS> </PropertyGroup> <ItemGroup> <LinuxPackageDependency Include="libopenssl1_0_0;libicu;krb5" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.Build.NoTargets"> <PropertyGroup> <GenerateInstallers Condition="'$(BuildRpmPackage)' != 'true'">false</GenerateInstallers> <PackageTargetOS>opensuse.42</PackageTargetOS> </PropertyGroup> <ItemGroup> <LinuxPackageDependency Include="libopenssl1_0_0;libicu;krb5" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Diagnostics.EventLog/src/Messages/readme.md
These files are used to produce an Event Message File. For more information see https://docs.microsoft.com/en-us/windows/win32/eventlog/message-files. The design of the EventLog class is to allow for the registration of event sources without specifying message files. In the case an event source does not specify it's own message file, EventLog just provides a default message file with 64K message IDs all that just pass through the first insertion string. This allow the event source to still use IDs for messages, but doesn't require the caller to actually pass a message file in order to achieve this. The process for producing the message file requires mc.exe and rc.exe which do not work cross-platform, and they require a VS install with C++ tools. Since these files rarely (if ever) change, we just use a manual process for updating this res file. To update the checked in files, manually run generateEventLogMessagesRes.cmd from a Developer Command Prompt.
These files are used to produce an Event Message File. For more information see https://docs.microsoft.com/en-us/windows/win32/eventlog/message-files. The design of the EventLog class is to allow for the registration of event sources without specifying message files. In the case an event source does not specify it's own message file, EventLog just provides a default message file with 64K message IDs all that just pass through the first insertion string. This allow the event source to still use IDs for messages, but doesn't require the caller to actually pass a message file in order to achieve this. The process for producing the message file requires mc.exe and rc.exe which do not work cross-platform, and they require a VS install with C++ tools. Since these files rarely (if ever) change, we just use a manual process for updating this res file. To update the checked in files, manually run generateEventLogMessagesRes.cmd from a Developer Command Prompt.
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Diagnostics.EventLog/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <SupportedOSPlatforms>windows</SupportedOSPlatforms> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <SupportedOSPlatforms>windows</SupportedOSPlatforms> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Net.Requests/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> <IncludePlatformAttributes>true</IncludePlatformAttributes> <UnsupportedOSPlatforms>browser</UnsupportedOSPlatforms> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> <IncludePlatformAttributes>true</IncludePlatformAttributes> <UnsupportedOSPlatforms>browser</UnsupportedOSPlatforms> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Xml.ReaderWriter/System.Xml.ReaderWriter.sln
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Win32.Primitives", "..\Microsoft.Win32.Primitives\ref\Microsoft.Win32.Primitives.csproj", "{10E63FBC-BE6B-4681-A245-1AA7161C8326}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Collections.NonGeneric", "..\System.Collections.NonGeneric\ref\System.Collections.NonGeneric.csproj", "{7B96787D-9003-4941-A69B-A85690AA8B1D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Collections", "..\System.Collections\ref\System.Collections.csproj", "{BDF8FD53-4F15-4C57-B325-438299F50160}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Primitives", "..\System.Net.Primitives\ref\System.Net.Primitives.csproj", "{206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Xml", "..\System.Private.Xml\src\System.Private.Xml.csproj", "{4886A8C5-3546-459A-8800-ED0DA91C6B15}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.InteropServices", "..\System.Runtime.InteropServices\ref\System.Runtime.InteropServices.csproj", "{EB054118-BC71-4613-858D-841A42602F1A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime", "..\System.Runtime\ref\System.Runtime.csproj", "{64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.RegularExpressions.Generator", "..\System.Text.RegularExpressions\gen\System.Text.RegularExpressions.Generator.csproj", "{3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Xml.ReaderWriter", "ref\System.Xml.ReaderWriter.csproj", "{2FE5F437-4CE1-4A27-8547-B950F8043D89}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Xml.ReaderWriter", "src\System.Xml.ReaderWriter.csproj", "{FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{311C66CC-47AC-4965-B704-3C62E57FE29D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{DD1FA45A-B14C-49B5-87C8-1760B478FE91}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Debug|Any CPU.Build.0 = Debug|Any CPU {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Release|Any CPU.ActiveCfg = Release|Any CPU {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Release|Any CPU.Build.0 = Release|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Release|Any CPU.ActiveCfg = Release|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Release|Any CPU.Build.0 = Release|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Debug|Any CPU.Build.0 = Debug|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Release|Any CPU.ActiveCfg = Release|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Release|Any CPU.Build.0 = Release|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Debug|Any CPU.Build.0 = Debug|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Release|Any CPU.ActiveCfg = Release|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Release|Any CPU.Build.0 = Release|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Debug|Any CPU.Build.0 = Debug|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Release|Any CPU.ActiveCfg = Release|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Release|Any CPU.Build.0 = Release|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Debug|Any CPU.Build.0 = Debug|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Release|Any CPU.ActiveCfg = Release|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Release|Any CPU.Build.0 = Release|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Release|Any CPU.Build.0 = Release|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Debug|Any CPU.Build.0 = Debug|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Release|Any CPU.ActiveCfg = Release|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Release|Any CPU.Build.0 = Release|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Debug|Any CPU.Build.0 = Debug|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Release|Any CPU.ActiveCfg = Release|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Release|Any CPU.Build.0 = Release|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Debug|Any CPU.Build.0 = Debug|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Release|Any CPU.ActiveCfg = Release|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Release|Any CPU.Build.0 = Release|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Debug|Any CPU.Build.0 = Debug|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Release|Any CPU.ActiveCfg = Release|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Release|Any CPU.Build.0 = Release|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Debug|Any CPU.Build.0 = Debug|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {10E63FBC-BE6B-4681-A245-1AA7161C8326} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {7B96787D-9003-4941-A69B-A85690AA8B1D} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {BDF8FD53-4F15-4C57-B325-438299F50160} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {EB054118-BC71-4613-858D-841A42602F1A} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {2FE5F437-4CE1-4A27-8547-B950F8043D89} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {4886A8C5-3546-459A-8800-ED0DA91C6B15} = {311C66CC-47AC-4965-B704-3C62E57FE29D} {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA} = {311C66CC-47AC-4965-B704-3C62E57FE29D} {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02} = {DD1FA45A-B14C-49B5-87C8-1760B478FE91} {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC} = {DD1FA45A-B14C-49B5-87C8-1760B478FE91} {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1} = {DD1FA45A-B14C-49B5-87C8-1760B478FE91} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B00449BC-6738-4BD0-A908-5DE1002A348C} EndGlobalSection EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Win32.Primitives", "..\Microsoft.Win32.Primitives\ref\Microsoft.Win32.Primitives.csproj", "{10E63FBC-BE6B-4681-A245-1AA7161C8326}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Collections.NonGeneric", "..\System.Collections.NonGeneric\ref\System.Collections.NonGeneric.csproj", "{7B96787D-9003-4941-A69B-A85690AA8B1D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Collections", "..\System.Collections\ref\System.Collections.csproj", "{BDF8FD53-4F15-4C57-B325-438299F50160}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Primitives", "..\System.Net.Primitives\ref\System.Net.Primitives.csproj", "{206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Xml", "..\System.Private.Xml\src\System.Private.Xml.csproj", "{4886A8C5-3546-459A-8800-ED0DA91C6B15}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.InteropServices", "..\System.Runtime.InteropServices\ref\System.Runtime.InteropServices.csproj", "{EB054118-BC71-4613-858D-841A42602F1A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime", "..\System.Runtime\ref\System.Runtime.csproj", "{64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.RegularExpressions.Generator", "..\System.Text.RegularExpressions\gen\System.Text.RegularExpressions.Generator.csproj", "{3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Xml.ReaderWriter", "ref\System.Xml.ReaderWriter.csproj", "{2FE5F437-4CE1-4A27-8547-B950F8043D89}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Xml.ReaderWriter", "src\System.Xml.ReaderWriter.csproj", "{FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{311C66CC-47AC-4965-B704-3C62E57FE29D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{DD1FA45A-B14C-49B5-87C8-1760B478FE91}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Debug|Any CPU.Build.0 = Debug|Any CPU {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Release|Any CPU.ActiveCfg = Release|Any CPU {10E63FBC-BE6B-4681-A245-1AA7161C8326}.Release|Any CPU.Build.0 = Release|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Release|Any CPU.ActiveCfg = Release|Any CPU {7B96787D-9003-4941-A69B-A85690AA8B1D}.Release|Any CPU.Build.0 = Release|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Debug|Any CPU.Build.0 = Debug|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Release|Any CPU.ActiveCfg = Release|Any CPU {BDF8FD53-4F15-4C57-B325-438299F50160}.Release|Any CPU.Build.0 = Release|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Debug|Any CPU.Build.0 = Debug|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Release|Any CPU.ActiveCfg = Release|Any CPU {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F}.Release|Any CPU.Build.0 = Release|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Debug|Any CPU.Build.0 = Debug|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Release|Any CPU.ActiveCfg = Release|Any CPU {4886A8C5-3546-459A-8800-ED0DA91C6B15}.Release|Any CPU.Build.0 = Release|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Debug|Any CPU.Build.0 = Debug|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Release|Any CPU.ActiveCfg = Release|Any CPU {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02}.Release|Any CPU.Build.0 = Release|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC}.Release|Any CPU.Build.0 = Release|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Debug|Any CPU.Build.0 = Debug|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Release|Any CPU.ActiveCfg = Release|Any CPU {EB054118-BC71-4613-858D-841A42602F1A}.Release|Any CPU.Build.0 = Release|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Debug|Any CPU.Build.0 = Debug|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Release|Any CPU.ActiveCfg = Release|Any CPU {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B}.Release|Any CPU.Build.0 = Release|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Debug|Any CPU.Build.0 = Debug|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Release|Any CPU.ActiveCfg = Release|Any CPU {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1}.Release|Any CPU.Build.0 = Release|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Debug|Any CPU.Build.0 = Debug|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Release|Any CPU.ActiveCfg = Release|Any CPU {2FE5F437-4CE1-4A27-8547-B950F8043D89}.Release|Any CPU.Build.0 = Release|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Debug|Any CPU.Build.0 = Debug|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {10E63FBC-BE6B-4681-A245-1AA7161C8326} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {7B96787D-9003-4941-A69B-A85690AA8B1D} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {BDF8FD53-4F15-4C57-B325-438299F50160} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {206F2168-FE78-4ABC-89A6-85AD5BAE2E5F} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {EB054118-BC71-4613-858D-841A42602F1A} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {64EEBBBD-FD43-4880-8C9C-E156BF15FC7B} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {2FE5F437-4CE1-4A27-8547-B950F8043D89} = {6AA53AA1-786A-4B35-B1C5-9D3B2EC10CF1} {4886A8C5-3546-459A-8800-ED0DA91C6B15} = {311C66CC-47AC-4965-B704-3C62E57FE29D} {FA7C251C-D1FD-45C3-8CC8-D094F70A03AA} = {311C66CC-47AC-4965-B704-3C62E57FE29D} {CA8BC7D5-9A5D-4055-BE69-6D469B38ED02} = {DD1FA45A-B14C-49B5-87C8-1760B478FE91} {640CCB13-BBC5-4B1A-90ED-87DA28BCA4AC} = {DD1FA45A-B14C-49B5-87C8-1760B478FE91} {3CCCB1F8-16A0-46BE-93D9-E11E22294CC1} = {DD1FA45A-B14C-49B5-87C8-1760B478FE91} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B00449BC-6738-4BD0-A908-5DE1002A348C} EndGlobalSection EndGlobal
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Security.Cryptography.OpenSsl/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> <IncludePlatformAttributes>true</IncludePlatformAttributes> <UnsupportedOSPlatforms>windows;browser;android;ios;tvos</UnsupportedOSPlatforms> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> <IncludePlatformAttributes>true</IncludePlatformAttributes> <UnsupportedOSPlatforms>windows;browser;android;ios;tvos</UnsupportedOSPlatforms> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./docs/project/list-of-diagnostics.md
# List of Diagnostics Produced by .NET Libraries APIs ## Obsoletions Per https://github.com/dotnet/designs/blob/master/accepted/2020/better-obsoletion/better-obsoletion.md, we now have a strategy for marking existing APIs as `[Obsolete]`. This takes advantage of the new diagnostic id and URL template mechanisms introduced to `ObsoleteAttribute` in .NET 5. The diagnostic id values reserved for obsoletions are `SYSLIB0001` through `SYSLIB0999`. When obsoleting an API, claim the next three-digit identifier in the `SYSLIB0###` sequence and add it to the list below. The URL template for all obsoletions is `https://aka.ms/dotnet-warnings/{0}`. The `{0}` placeholder is replaced by the compiler with the `SYSLIB0###` identifier. The acceptance criteria for adding an obsoletion includes: * Add the obsoletion to the table below, claiming the next diagnostic id * Ensure the description is meaningful within the context of this table, and without requiring the context of the calling code * Add new constants to `src\libraries\Common\src\System\Obsoletions.cs`, following the existing conventions * A `...Message` const using the same description added to the table below * A `...DiagId` const for the `SYSLIB0###` id * Annotate `src` files by referring to the constants defined from `Obsoletions.cs` * Specify the `UrlFormat = Obsoletions.SharedUrlFormat` * Example: `[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]` * If the `Obsoletions` type is not available in the project, link it into the project * `<Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" />` * Annotate `ref` files using the hard-coded strings copied from `Obsoletions.cs` * This matches our general pattern of `ref` files using hard-coded attribute strings * Example: `[System.ObsoleteAttribute("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.", DiagnosticId = "SYSLIB0001", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]` * If the library builds against downlevel targets earlier than .NET 5.0, then add an internal copy of `ObsoleteAttribute` * The compiler recognizes internal implementations of `ObsoleteAttribute` to enable the `DiagnosticId` and `UrlFormat` properties to light up downlevel * An MSBuild property can be added to the project's first `<PropertyGroup>` to achieve this easily * Example: `<IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>` * This will need to be specified in both the `src` and `ref` projects * If the library contains types that are forwarded within a generated shim * Errors will be received when running `build libs`, with obsoletion errors in `src/libraries/shims/generated` files * This is resolved by adding the obsoletion's diagnostic id to the `<NoWarn>` property for partial facade assemblies * That property is found in `src/libraries/Directory.Build.targets` * Search for the "Ignore Obsolete errors within the generated shims that type-forward types" comment and add the appropriate diagnostic id to the comment and the `<NoWarn>` property (other SYSLIB diagnostics already exist there) * Apply the `breaking-change` label to the PR that introduces the obsoletion * A bot will automatically apply the `needs-breaking-change-doc-created` label when the `breaking-change` label is detected * Follow up with the breaking change process to communicate and document the breaking change * In the breaking-change issue filed in [dotnet/docs](https://github.com/dotnet/docs), specifically mention that this breaking change is an obsoletion with a `SYSLIB` diagnostic id * The documentation team will produce a PR that adds the obsoletion to the [SYSLIB warnings](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-obsoletions) page * That PR will also add a new URL specific to this diagnostic ID; e.g. [SYSLIB0001](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-warnings/syslib0001) * Connect with `@gewarren` or `@BillWagner` with any questions * Register the `SYSLIB0###` URL in `aka.ms` * The vanity name will be `dotnet-warnings/syslib0###` * Ensure the link's group owner matches the group owner of `dotnet-warnings/syslib0001` * Connect with `@jeffhandley`, `@GrabYourPitchforks`, or `@gewarren` with any questions An example obsoletion PR that can be referenced where each of the above criteria was met is: * [Implement new GetContextAPI overloads (#49186)](https://github.com/dotnet/runtime/pull/49186/files) The PR that reveals the implementation of the `<IncludeInternalObsoleteAttribute>` property was: * [Mark DirectoryServices CAS APIs as Obsolete (#40756)](https://github.com/dotnet/runtime/pull/40756/files) ### Obsoletion Diagnostics (`SYSLIB0001` - `SYSLIB0999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB0001`__ | The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead. | | __`SYSLIB0002`__ | PrincipalPermissionAttribute is not honored by the runtime and must not be used. | | __`SYSLIB0003`__ | Code Access Security is not supported or honored by the runtime. | | __`SYSLIB0004`__ | The Constrained Execution Region (CER) feature is not supported. | | __`SYSLIB0005`__ | The Global Assembly Cache is not supported. | | __`SYSLIB0006`__ | Thread.Abort is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0007`__ | The default implementation of this cryptography algorithm is not supported. | | __`SYSLIB0008`__ | The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0009`__ | The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0010`__ | This Remoting API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0011`__ | `BinaryFormatter` serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for recommended alternatives. | | __`SYSLIB0012`__ | Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead. | | __`SYSLIB0013`__ | Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead. | | __`SYSLIB0014`__ | WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead. | | __`SYSLIB0015`__ | DisablePrivateReflectionAttribute has no effect in .NET 6.0+. | | __`SYSLIB0016`__ | Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations. | | __`SYSLIB0017`__ | Strong name signing is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0018`__ | ReflectionOnly loading is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0019`__ | RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0020`__ | JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull. | | __`SYSLIB0021`__ | Derived cryptographic types are obsolete. Use the Create method on the base type instead. | | __`SYSLIB0022`__ | The Rijndael and RijndaelManaged types are obsolete. Use Aes instead. | | __`SYSLIB0023`__ | RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead. | | __`SYSLIB0024`__ | Creating and unloading AppDomains is not supported and throws an exception. | | __`SYSLIB0025`__ | SuppressIldasmAttribute has no effect in .NET 6.0+. | | __`SYSLIB0026`__ | X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate. | | __`SYSLIB0027`__ | PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey. | | __`SYSLIB0028`__ | X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key. | | __`SYSLIB0029`__ | ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported. | | __`SYSLIB0030`__ | HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter. | | __`SYSLIB0031`__ | EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1. | | __`SYSLIB0032`__ | Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored. | | __`SYSLIB0033`__ | Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead. | | __`SYSLIB0034`__ | CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead. | | __`SYSLIB0035`__ | ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner. | | __`SYSLIB0036`__ | Regex.CompileToAssembly is obsolete and not supported. Use RegexGeneratorAttribute with the regular expression source generator instead. | | __`SYSLIB0037`__ | AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported. | | __`SYSLIB0038`__ | SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information. | | __`SYSLIB0039`__ | TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults. | | __`SYSLIB0040`__ | EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code. | | __`SYSLIB0041`__ | The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations. | | __`SYSLIB0042`__ | ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys. | | __`SYSLIB0043`__ | ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead. | ## Analyzer Warnings The diagnostic id values reserved for .NET Libraries analyzer warnings are `SYSLIB1001` through `SYSLIB1999`. When creating a new analyzer that ships as part of the Libraries (and not part of the SDK), claim the next three-digit identifier in the `SYSLIB1###` sequence and add it to the list below. ### Analyzer Diagnostics (`SYSLIB1001` - `SYSLIB1999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB1001`__ | Logging method names cannot start with _ | | __`SYSLIB1002`__ | Don't include log level parameters as templates in the logging message | | __`SYSLIB1003`__ | InvalidLoggingMethodParameterNameTitle | | __`SYSLIB1004`__ | Logging class cannot be in nested types | | __`SYSLIB1005`__ | Could not find a required type definition | | __`SYSLIB1006`__ | Multiple logging methods cannot use the same event id within a class | | __`SYSLIB1007`__ | Logging methods must return void | | __`SYSLIB1008`__ | One of the arguments to a logging method must implement the Microsoft.Extensions.Logging.ILogger interface | | __`SYSLIB1009`__ | Logging methods must be static | | __`SYSLIB1010`__ | Logging methods must be partial | | __`SYSLIB1011`__ | Logging methods cannot be generic | | __`SYSLIB1012`__ | Redundant qualifier in logging message | | __`SYSLIB1013`__ | Don't include exception parameters as templates in the logging message | | __`SYSLIB1014`__ | Logging template has no corresponding method argument | | __`SYSLIB1015`__ | Argument is not referenced from the logging message | | __`SYSLIB1016`__ | Logging methods cannot have a body | | __`SYSLIB1017`__ | A LogLevel value must be supplied in the LoggerMessage attribute or as a parameter to the logging method | | __`SYSLIB1018`__ | Don't include logger parameters as templates in the logging message | | __`SYSLIB1019`__ | Couldn't find a field of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1020`__ | Found multiple fields of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1021`__ | Can't have the same template with different casing | | __`SYSLIB1022`__ | Can't have malformed format strings (like dangling {, etc) | | __`SYSLIB1023`__ | Generating more than 6 arguments is not supported | | __`SYSLIB1024`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1025`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1026`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1027`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1028`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1029`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1030`__ | JsonSourceGenerator did not generate serialization metadata for type | | __`SYSLIB1031`__ | JsonSourceGenerator encountered a duplicate JsonTypeInfo property name | | __`SYSLIB1032`__ | JsonSourceGenerator encountered a context class that is not partial | | __`SYSLIB1033`__ | JsonSourceGenerator encountered a type that has multiple [JsonConstructor] annotations| | __`SYSLIB1034`__ | *_`SYSLIB1034` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1035`__ | JsonSourceGenerator encountered a type that has multiple [JsonExtensionData] annotations | | __`SYSLIB1036`__ | JsonSourceGenerator encountered an invalid [JsonExtensionData] annotation | | __`SYSLIB1037`__ | JsonSourceGenerator encountered a type with init-only properties for which deserialization is not supported | | __`SYSLIB1038`__ | JsonSourceGenerator encountered a property annotated with [JsonInclude] that has inaccessible accessors | | __`SYSLIB1039`__ | *_`SYSLIB1039` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1040`__ | Invalid RegexGenerator attribute | | __`SYSLIB1041`__ | Multiple RegexGenerator attribute | | __`SYSLIB1042`__ | Invalid RegexGenerator arguments | | __`SYSLIB1043`__ | RegexGenerator method must have a valid signature | | __`SYSLIB1044`__ | RegexGenerator only supports C# 10 and newer | | __`SYSLIB1045`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1046`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1047`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1048`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1049`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1050`__ | Invalid LibraryImportAttribute usage | | __`SYSLIB1051`__ | Specified type is not supported by source-generated P/Invokes | | __`SYSLIB1052`__ | Specified configuration is not supported by source-generated P/Invokes | | __`SYSLIB1053`__ | Specified LibraryImportAttribute arguments cannot be forwarded to DllImportAttribute | | __`SYSLIB1054`__ | Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time | | __`SYSLIB1055`__ | Invalid CustomTypeMarshallerAttribute usage | | __`SYSLIB1056`__ | Specified native type is invalid | | __`SYSLIB1057`__ | Marshaller type does not have the required shape | | __`SYSLIB1058`__ | Marshaller type defines a well-known method without specifying support for the corresponding feature | | __`SYSLIB1059`__ | Marshaller type does not support allocating constructor | | __`SYSLIB1060`__ | BufferSize should be set on CustomTypeMarshallerAttribute | | __`SYSLIB1061`__ | Marshaller type has incompatible method signatures | | __`SYSLIB1062`__ | *_`SYSLIB1062`-`SYSLIB1064` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1063`__ | *_`SYSLIB1062`-`SYSLIB1064` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1064`__ | *_`SYSLIB1062`-`SYSLIB1064` reserved for Microsoft.Interop.LibraryImportGenerator._* |
# List of Diagnostics Produced by .NET Libraries APIs ## Obsoletions Per https://github.com/dotnet/designs/blob/master/accepted/2020/better-obsoletion/better-obsoletion.md, we now have a strategy for marking existing APIs as `[Obsolete]`. This takes advantage of the new diagnostic id and URL template mechanisms introduced to `ObsoleteAttribute` in .NET 5. The diagnostic id values reserved for obsoletions are `SYSLIB0001` through `SYSLIB0999`. When obsoleting an API, claim the next three-digit identifier in the `SYSLIB0###` sequence and add it to the list below. The URL template for all obsoletions is `https://aka.ms/dotnet-warnings/{0}`. The `{0}` placeholder is replaced by the compiler with the `SYSLIB0###` identifier. The acceptance criteria for adding an obsoletion includes: * Add the obsoletion to the table below, claiming the next diagnostic id * Ensure the description is meaningful within the context of this table, and without requiring the context of the calling code * Add new constants to `src\libraries\Common\src\System\Obsoletions.cs`, following the existing conventions * A `...Message` const using the same description added to the table below * A `...DiagId` const for the `SYSLIB0###` id * Annotate `src` files by referring to the constants defined from `Obsoletions.cs` * Specify the `UrlFormat = Obsoletions.SharedUrlFormat` * Example: `[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]` * If the `Obsoletions` type is not available in the project, link it into the project * `<Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" />` * Annotate `ref` files using the hard-coded strings copied from `Obsoletions.cs` * This matches our general pattern of `ref` files using hard-coded attribute strings * Example: `[System.ObsoleteAttribute("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.", DiagnosticId = "SYSLIB0001", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]` * If the library builds against downlevel targets earlier than .NET 5.0, then add an internal copy of `ObsoleteAttribute` * The compiler recognizes internal implementations of `ObsoleteAttribute` to enable the `DiagnosticId` and `UrlFormat` properties to light up downlevel * An MSBuild property can be added to the project's first `<PropertyGroup>` to achieve this easily * Example: `<IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>` * This will need to be specified in both the `src` and `ref` projects * If the library contains types that are forwarded within a generated shim * Errors will be received when running `build libs`, with obsoletion errors in `src/libraries/shims/generated` files * This is resolved by adding the obsoletion's diagnostic id to the `<NoWarn>` property for partial facade assemblies * That property is found in `src/libraries/Directory.Build.targets` * Search for the "Ignore Obsolete errors within the generated shims that type-forward types" comment and add the appropriate diagnostic id to the comment and the `<NoWarn>` property (other SYSLIB diagnostics already exist there) * Apply the `breaking-change` label to the PR that introduces the obsoletion * A bot will automatically apply the `needs-breaking-change-doc-created` label when the `breaking-change` label is detected * Follow up with the breaking change process to communicate and document the breaking change * In the breaking-change issue filed in [dotnet/docs](https://github.com/dotnet/docs), specifically mention that this breaking change is an obsoletion with a `SYSLIB` diagnostic id * The documentation team will produce a PR that adds the obsoletion to the [SYSLIB warnings](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-obsoletions) page * That PR will also add a new URL specific to this diagnostic ID; e.g. [SYSLIB0001](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-warnings/syslib0001) * Connect with `@gewarren` or `@BillWagner` with any questions * Register the `SYSLIB0###` URL in `aka.ms` * The vanity name will be `dotnet-warnings/syslib0###` * Ensure the link's group owner matches the group owner of `dotnet-warnings/syslib0001` * Connect with `@jeffhandley`, `@GrabYourPitchforks`, or `@gewarren` with any questions An example obsoletion PR that can be referenced where each of the above criteria was met is: * [Implement new GetContextAPI overloads (#49186)](https://github.com/dotnet/runtime/pull/49186/files) The PR that reveals the implementation of the `<IncludeInternalObsoleteAttribute>` property was: * [Mark DirectoryServices CAS APIs as Obsolete (#40756)](https://github.com/dotnet/runtime/pull/40756/files) ### Obsoletion Diagnostics (`SYSLIB0001` - `SYSLIB0999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB0001`__ | The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead. | | __`SYSLIB0002`__ | PrincipalPermissionAttribute is not honored by the runtime and must not be used. | | __`SYSLIB0003`__ | Code Access Security is not supported or honored by the runtime. | | __`SYSLIB0004`__ | The Constrained Execution Region (CER) feature is not supported. | | __`SYSLIB0005`__ | The Global Assembly Cache is not supported. | | __`SYSLIB0006`__ | Thread.Abort is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0007`__ | The default implementation of this cryptography algorithm is not supported. | | __`SYSLIB0008`__ | The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0009`__ | The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0010`__ | This Remoting API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0011`__ | `BinaryFormatter` serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for recommended alternatives. | | __`SYSLIB0012`__ | Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead. | | __`SYSLIB0013`__ | Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead. | | __`SYSLIB0014`__ | WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead. | | __`SYSLIB0015`__ | DisablePrivateReflectionAttribute has no effect in .NET 6.0+. | | __`SYSLIB0016`__ | Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations. | | __`SYSLIB0017`__ | Strong name signing is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0018`__ | ReflectionOnly loading is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0019`__ | RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0020`__ | JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull. | | __`SYSLIB0021`__ | Derived cryptographic types are obsolete. Use the Create method on the base type instead. | | __`SYSLIB0022`__ | The Rijndael and RijndaelManaged types are obsolete. Use Aes instead. | | __`SYSLIB0023`__ | RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead. | | __`SYSLIB0024`__ | Creating and unloading AppDomains is not supported and throws an exception. | | __`SYSLIB0025`__ | SuppressIldasmAttribute has no effect in .NET 6.0+. | | __`SYSLIB0026`__ | X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate. | | __`SYSLIB0027`__ | PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey. | | __`SYSLIB0028`__ | X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key. | | __`SYSLIB0029`__ | ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported. | | __`SYSLIB0030`__ | HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter. | | __`SYSLIB0031`__ | EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1. | | __`SYSLIB0032`__ | Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored. | | __`SYSLIB0033`__ | Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead. | | __`SYSLIB0034`__ | CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead. | | __`SYSLIB0035`__ | ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner. | | __`SYSLIB0036`__ | Regex.CompileToAssembly is obsolete and not supported. Use RegexGeneratorAttribute with the regular expression source generator instead. | | __`SYSLIB0037`__ | AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported. | | __`SYSLIB0038`__ | SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information. | | __`SYSLIB0039`__ | TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults. | | __`SYSLIB0040`__ | EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code. | | __`SYSLIB0041`__ | The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations. | | __`SYSLIB0042`__ | ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys. | | __`SYSLIB0043`__ | ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead. | ## Analyzer Warnings The diagnostic id values reserved for .NET Libraries analyzer warnings are `SYSLIB1001` through `SYSLIB1999`. When creating a new analyzer that ships as part of the Libraries (and not part of the SDK), claim the next three-digit identifier in the `SYSLIB1###` sequence and add it to the list below. ### Analyzer Diagnostics (`SYSLIB1001` - `SYSLIB1999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB1001`__ | Logging method names cannot start with _ | | __`SYSLIB1002`__ | Don't include log level parameters as templates in the logging message | | __`SYSLIB1003`__ | InvalidLoggingMethodParameterNameTitle | | __`SYSLIB1004`__ | Logging class cannot be in nested types | | __`SYSLIB1005`__ | Could not find a required type definition | | __`SYSLIB1006`__ | Multiple logging methods cannot use the same event id within a class | | __`SYSLIB1007`__ | Logging methods must return void | | __`SYSLIB1008`__ | One of the arguments to a logging method must implement the Microsoft.Extensions.Logging.ILogger interface | | __`SYSLIB1009`__ | Logging methods must be static | | __`SYSLIB1010`__ | Logging methods must be partial | | __`SYSLIB1011`__ | Logging methods cannot be generic | | __`SYSLIB1012`__ | Redundant qualifier in logging message | | __`SYSLIB1013`__ | Don't include exception parameters as templates in the logging message | | __`SYSLIB1014`__ | Logging template has no corresponding method argument | | __`SYSLIB1015`__ | Argument is not referenced from the logging message | | __`SYSLIB1016`__ | Logging methods cannot have a body | | __`SYSLIB1017`__ | A LogLevel value must be supplied in the LoggerMessage attribute or as a parameter to the logging method | | __`SYSLIB1018`__ | Don't include logger parameters as templates in the logging message | | __`SYSLIB1019`__ | Couldn't find a field of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1020`__ | Found multiple fields of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1021`__ | Can't have the same template with different casing | | __`SYSLIB1022`__ | Can't have malformed format strings (like dangling {, etc) | | __`SYSLIB1023`__ | Generating more than 6 arguments is not supported | | __`SYSLIB1024`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1025`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1026`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1027`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1028`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1029`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1030`__ | JsonSourceGenerator did not generate serialization metadata for type | | __`SYSLIB1031`__ | JsonSourceGenerator encountered a duplicate JsonTypeInfo property name | | __`SYSLIB1032`__ | JsonSourceGenerator encountered a context class that is not partial | | __`SYSLIB1033`__ | JsonSourceGenerator encountered a type that has multiple [JsonConstructor] annotations| | __`SYSLIB1034`__ | *_`SYSLIB1034` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1035`__ | JsonSourceGenerator encountered a type that has multiple [JsonExtensionData] annotations | | __`SYSLIB1036`__ | JsonSourceGenerator encountered an invalid [JsonExtensionData] annotation | | __`SYSLIB1037`__ | JsonSourceGenerator encountered a type with init-only properties for which deserialization is not supported | | __`SYSLIB1038`__ | JsonSourceGenerator encountered a property annotated with [JsonInclude] that has inaccessible accessors | | __`SYSLIB1039`__ | *_`SYSLIB1039` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1040`__ | Invalid RegexGenerator attribute | | __`SYSLIB1041`__ | Multiple RegexGenerator attribute | | __`SYSLIB1042`__ | Invalid RegexGenerator arguments | | __`SYSLIB1043`__ | RegexGenerator method must have a valid signature | | __`SYSLIB1044`__ | RegexGenerator only supports C# 10 and newer | | __`SYSLIB1045`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1046`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1047`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1048`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1049`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1050`__ | Invalid LibraryImportAttribute usage | | __`SYSLIB1051`__ | Specified type is not supported by source-generated P/Invokes | | __`SYSLIB1052`__ | Specified configuration is not supported by source-generated P/Invokes | | __`SYSLIB1053`__ | Specified LibraryImportAttribute arguments cannot be forwarded to DllImportAttribute | | __`SYSLIB1054`__ | Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time | | __`SYSLIB1055`__ | Invalid CustomTypeMarshallerAttribute usage | | __`SYSLIB1056`__ | Specified native type is invalid | | __`SYSLIB1057`__ | Marshaller type does not have the required shape | | __`SYSLIB1058`__ | Marshaller type defines a well-known method without specifying support for the corresponding feature | | __`SYSLIB1059`__ | Marshaller type does not support allocating constructor | | __`SYSLIB1060`__ | BufferSize should be set on CustomTypeMarshallerAttribute | | __`SYSLIB1061`__ | Marshaller type has incompatible method signatures | | __`SYSLIB1062`__ | *_`SYSLIB1062`-`SYSLIB1064` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1063`__ | *_`SYSLIB1062`-`SYSLIB1064` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1064`__ | *_`SYSLIB1062`-`SYSLIB1064` reserved for Microsoft.Interop.LibraryImportGenerator._* |
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/System.Private.CoreLib/System.Private.CoreLib.sln
Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.28902.138 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "System.Private.CoreLib.csproj", "{8FBEB036-6F52-464C-8BC9-B0B5F18262A6}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "System.Private.CoreLib.Shared", "..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.shproj", "{845C8B26-350B-4E63-BD11-2C8150444E28}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib.Generators", "..\..\libraries\System.Private.CoreLib\gen\System.Private.CoreLib.Generators.csproj", "{A4CD9C83-5937-46B7-A1F2-1990F5B938E7}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{845c8b26-350b-4e63-bd11-2c8150444e28}*SharedItemsImports = 13 ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{8fbeb036-6f52-464c-8bc9-b0b5f18262a6}*SharedItemsImports = 5 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Checked|amd64 = Checked|amd64 Checked|Any CPU = Checked|Any CPU Checked|arm = Checked|arm Checked|arm64 = Checked|arm64 Checked|wasm32 = Checked|wasm32 Checked|x86 = Checked|x86 Debug|amd64 = Debug|amd64 Debug|Any CPU = Debug|Any CPU Debug|arm = Debug|arm Debug|arm64 = Debug|arm64 Debug|wasm32 = Debug|wasm32 Debug|x86 = Debug|x86 Release|amd64 = Release|amd64 Release|Any CPU = Release|Any CPU Release|arm = Release|arm Release|arm64 = Release|arm64 Release|wasm32 = Release|wasm32 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|amd64.ActiveCfg = Checked|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|amd64.Build.0 = Checked|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|Any CPU.ActiveCfg = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm.ActiveCfg = Checked|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm.Build.0 = Checked|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm64.ActiveCfg = Checked|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm64.Build.0 = Checked|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|wasm32.ActiveCfg = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|x86.ActiveCfg = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|x86.Build.0 = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|amd64.ActiveCfg = Debug|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|amd64.Build.0 = Debug|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|Any CPU.ActiveCfg = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm.ActiveCfg = Debug|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm.Build.0 = Debug|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm64.ActiveCfg = Debug|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm64.Build.0 = Debug|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|wasm32.ActiveCfg = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|x86.ActiveCfg = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|x86.Build.0 = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|amd64.ActiveCfg = Release|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|amd64.Build.0 = Release|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|Any CPU.ActiveCfg = Release|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm.ActiveCfg = Release|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm.Build.0 = Release|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm64.ActiveCfg = Release|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm64.Build.0 = Release|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|wasm32.ActiveCfg = Release|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|x86.ActiveCfg = Release|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|x86.Build.0 = Release|x86 {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|amd64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|amd64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|Any CPU.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|wasm32.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|wasm32.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|x86.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|x86.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|amd64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|amd64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|wasm32.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|wasm32.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|x86.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|x86.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|amd64.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|amd64.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|Any CPU.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm64.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm64.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|wasm32.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|wasm32.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|x86.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {48FC8980-C27D-47CB-B4A6-BFF2AC21D716} EndGlobalSection EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.28902.138 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "System.Private.CoreLib.csproj", "{8FBEB036-6F52-464C-8BC9-B0B5F18262A6}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "System.Private.CoreLib.Shared", "..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.shproj", "{845C8B26-350B-4E63-BD11-2C8150444E28}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib.Generators", "..\..\libraries\System.Private.CoreLib\gen\System.Private.CoreLib.Generators.csproj", "{A4CD9C83-5937-46B7-A1F2-1990F5B938E7}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{845c8b26-350b-4e63-bd11-2c8150444e28}*SharedItemsImports = 13 ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{8fbeb036-6f52-464c-8bc9-b0b5f18262a6}*SharedItemsImports = 5 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Checked|amd64 = Checked|amd64 Checked|Any CPU = Checked|Any CPU Checked|arm = Checked|arm Checked|arm64 = Checked|arm64 Checked|wasm32 = Checked|wasm32 Checked|x86 = Checked|x86 Debug|amd64 = Debug|amd64 Debug|Any CPU = Debug|Any CPU Debug|arm = Debug|arm Debug|arm64 = Debug|arm64 Debug|wasm32 = Debug|wasm32 Debug|x86 = Debug|x86 Release|amd64 = Release|amd64 Release|Any CPU = Release|Any CPU Release|arm = Release|arm Release|arm64 = Release|arm64 Release|wasm32 = Release|wasm32 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|amd64.ActiveCfg = Checked|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|amd64.Build.0 = Checked|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|Any CPU.ActiveCfg = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm.ActiveCfg = Checked|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm.Build.0 = Checked|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm64.ActiveCfg = Checked|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|arm64.Build.0 = Checked|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|wasm32.ActiveCfg = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|x86.ActiveCfg = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Checked|x86.Build.0 = Checked|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|amd64.ActiveCfg = Debug|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|amd64.Build.0 = Debug|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|Any CPU.ActiveCfg = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm.ActiveCfg = Debug|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm.Build.0 = Debug|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm64.ActiveCfg = Debug|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|arm64.Build.0 = Debug|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|wasm32.ActiveCfg = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|x86.ActiveCfg = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Debug|x86.Build.0 = Debug|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|amd64.ActiveCfg = Release|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|amd64.Build.0 = Release|x64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|Any CPU.ActiveCfg = Release|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm.ActiveCfg = Release|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm.Build.0 = Release|arm {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm64.ActiveCfg = Release|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|arm64.Build.0 = Release|arm64 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|wasm32.ActiveCfg = Release|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|x86.ActiveCfg = Release|x86 {8FBEB036-6F52-464C-8BC9-B0B5F18262A6}.Release|x86.Build.0 = Release|x86 {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|amd64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|amd64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|Any CPU.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|arm64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|wasm32.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|wasm32.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|x86.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Checked|x86.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|amd64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|amd64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm64.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|arm64.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|wasm32.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|wasm32.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|x86.ActiveCfg = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Debug|x86.Build.0 = Debug|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|amd64.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|amd64.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|Any CPU.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm64.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|arm64.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|wasm32.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|wasm32.Build.0 = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|x86.ActiveCfg = Release|Any CPU {A4CD9C83-5937-46B7-A1F2-1990F5B938E7}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {48FC8980-C27D-47CB-B4A6-BFF2AC21D716} EndGlobalSection EndGlobal
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/Common/CLRTest.Execute.targets
<!-- *********************************************************************************************** CLRTest.Execute.targets WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have created a backup copy. Incorrect changes to this file will make it impossible to load or build your projects from the command-line or the IDE. This file contains the logic for providing Execution Script generation. *********************************************************************************************** --> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- ******************************************************************************************* PROPERTIES/ITEMS: Used when prepping a test for execution --> <!-- Temporary Defaults --> <PropertyGroup> <_CLRTestNeedsToRun Condition=" '$(_CLRTestNeedsToRun)' == '' ">true</_CLRTestNeedsToRun> <_CLRTestBuildsExecutable Condition=" '$(_CLRTestBuildsExecutable)' == '' ">true</_CLRTestBuildsExecutable> <CLRTestIsHosted Condition=" '$(CLRTestIsHosted)' == '' ">true</CLRTestIsHosted> <_CLRTestNeedsProjectToRun Condition=" '$(_CLRTestNeedsProjectToRun)' == '' ">false</_CLRTestNeedsProjectToRun> </PropertyGroup> <!-- When using a custom test entry-point other than corerun, the entry point is likely not going to be a managed app. So, we automatically disable test runs that assume corerun is the entry native executable. --> <PropertyGroup Condition="'$(CLRTestIsHosted)' != 'true'"> <UnloadabilityIncompatible Condition="'$(UnloadabilityIncompatible)' == ''">true</UnloadabilityIncompatible> <TieringTestIncompatible Condition="'$(TieringTestIncompatible)' == ''">true</TieringTestIncompatible> </PropertyGroup> <PropertyGroup> <!-- TODO:1 Get the right guidance for overriding the default --> <CLRTestExitCode Condition=" '$(CLRTestExitCode)' == '' ">100</CLRTestExitCode> </PropertyGroup> <ItemDefinitionGroup> <CLRTestExecutionScriptArgument> <HasParam>false</HasParam> </CLRTestExecutionScriptArgument> </ItemDefinitionGroup> <!-- ******************************************************************************************* TARGET: GenerateExecutionScript TODO: get rid of this! The PreCheckin system depends directly on this target (boo). This makes sure the script ends up in the right place. --> <Target Name="GenerateExecutionScript" DependsOnTargets="GenerateExecutionScriptsInternal"/> <!-- ******************************************************************************************* TARGET: GenerateExecutionScriptsInternal For tests that "run" we will generate an execution script that wraps any arguments or other goo. This allows generated .lst files to be very simple and reusable to invoke any "stage" of test execution. Notice this is hooked up to run after targets that generate the stores that are marked with GenerateScripts metadata. Note also that this means it will run after the first of such targets. --> <ItemGroup> <ExecutionScriptKind Include="Batch" Condition="'$(TestWrapperTargetsWindows)' == 'true'" /> <ExecutionScriptKind Include="Bash" Condition="'$(TestWrapperTargetsWindows)' != 'true'" /> </ItemGroup> <PropertyGroup> <BashScriptSnippetGen></BashScriptSnippetGen> <BatchScriptSnippetGen></BatchScriptSnippetGen> <GetExecuteScriptTarget>GetExecuteShFullPath</GetExecuteScriptTarget> <GetExecuteScriptTarget Condition="'$(TestWrapperTargetsWindows)' == 'true'">GetExecuteCmdFullPath</GetExecuteScriptTarget> </PropertyGroup> <Import Project="CLRTest.Jit.targets" /> <Import Project="CLRTest.CrossGen.targets" /> <Import Project="CLRTest.GC.targets" /> <Import Project="CLRTest.Execute.*.targets" /> <Import Project="CLRTest.MockHosting.targets" Condition="'$(RequiresMockHostPolicy)' == 'true'" /> <Target Name="FetchExternalProperties"> <!--Call GetExecuteShFullPath to get ToRunProject cmd file Path --> <MSBuild Projects="$(CLRTestProjectToRun)" Targets="$(GetExecuteScriptTarget)" Properties="GenerateRunScript=True" Condition="'$(_CLRTestNeedsProjectToRun)' == 'True'"> <Output TaskParameter="TargetOutputs" PropertyName="_CLRTestToRunFileFullPath"/> </MSBuild> <PropertyGroup> <InputAssemblyName Condition="'$(CLRTestKind)' == 'RunOnly'">$([MSBuild]::MakeRelative($(OutputPath), $(_CLRTestToRunFileFullPath)))</InputAssemblyName> <InputAssemblyName Condition="'$(CLRTestKind)' == 'BuildAndRun'">$(AssemblyName).dll</InputAssemblyName> </PropertyGroup> </Target> <Target Name="GenerateExecutionScriptsInternal" Condition="$(_CLRTestNeedsToRun) or $(_CLRTestBuildsExecutable)" DependsOnTargets="FetchExternalProperties;Generate@(ExecutionScriptKind, 'ExecutionScript;Generate')ExecutionScript;" /> </Project>
<!-- *********************************************************************************************** CLRTest.Execute.targets WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have created a backup copy. Incorrect changes to this file will make it impossible to load or build your projects from the command-line or the IDE. This file contains the logic for providing Execution Script generation. *********************************************************************************************** --> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- ******************************************************************************************* PROPERTIES/ITEMS: Used when prepping a test for execution --> <!-- Temporary Defaults --> <PropertyGroup> <_CLRTestNeedsToRun Condition=" '$(_CLRTestNeedsToRun)' == '' ">true</_CLRTestNeedsToRun> <_CLRTestBuildsExecutable Condition=" '$(_CLRTestBuildsExecutable)' == '' ">true</_CLRTestBuildsExecutable> <CLRTestIsHosted Condition=" '$(CLRTestIsHosted)' == '' ">true</CLRTestIsHosted> <_CLRTestNeedsProjectToRun Condition=" '$(_CLRTestNeedsProjectToRun)' == '' ">false</_CLRTestNeedsProjectToRun> </PropertyGroup> <!-- When using a custom test entry-point other than corerun, the entry point is likely not going to be a managed app. So, we automatically disable test runs that assume corerun is the entry native executable. --> <PropertyGroup Condition="'$(CLRTestIsHosted)' != 'true'"> <UnloadabilityIncompatible Condition="'$(UnloadabilityIncompatible)' == ''">true</UnloadabilityIncompatible> <TieringTestIncompatible Condition="'$(TieringTestIncompatible)' == ''">true</TieringTestIncompatible> </PropertyGroup> <PropertyGroup> <!-- TODO:1 Get the right guidance for overriding the default --> <CLRTestExitCode Condition=" '$(CLRTestExitCode)' == '' ">100</CLRTestExitCode> </PropertyGroup> <ItemDefinitionGroup> <CLRTestExecutionScriptArgument> <HasParam>false</HasParam> </CLRTestExecutionScriptArgument> </ItemDefinitionGroup> <!-- ******************************************************************************************* TARGET: GenerateExecutionScript TODO: get rid of this! The PreCheckin system depends directly on this target (boo). This makes sure the script ends up in the right place. --> <Target Name="GenerateExecutionScript" DependsOnTargets="GenerateExecutionScriptsInternal"/> <!-- ******************************************************************************************* TARGET: GenerateExecutionScriptsInternal For tests that "run" we will generate an execution script that wraps any arguments or other goo. This allows generated .lst files to be very simple and reusable to invoke any "stage" of test execution. Notice this is hooked up to run after targets that generate the stores that are marked with GenerateScripts metadata. Note also that this means it will run after the first of such targets. --> <ItemGroup> <ExecutionScriptKind Include="Batch" Condition="'$(TestWrapperTargetsWindows)' == 'true'" /> <ExecutionScriptKind Include="Bash" Condition="'$(TestWrapperTargetsWindows)' != 'true'" /> </ItemGroup> <PropertyGroup> <BashScriptSnippetGen></BashScriptSnippetGen> <BatchScriptSnippetGen></BatchScriptSnippetGen> <GetExecuteScriptTarget>GetExecuteShFullPath</GetExecuteScriptTarget> <GetExecuteScriptTarget Condition="'$(TestWrapperTargetsWindows)' == 'true'">GetExecuteCmdFullPath</GetExecuteScriptTarget> </PropertyGroup> <Import Project="CLRTest.Jit.targets" /> <Import Project="CLRTest.CrossGen.targets" /> <Import Project="CLRTest.GC.targets" /> <Import Project="CLRTest.Execute.*.targets" /> <Import Project="CLRTest.MockHosting.targets" Condition="'$(RequiresMockHostPolicy)' == 'true'" /> <Target Name="FetchExternalProperties"> <!--Call GetExecuteShFullPath to get ToRunProject cmd file Path --> <MSBuild Projects="$(CLRTestProjectToRun)" Targets="$(GetExecuteScriptTarget)" Properties="GenerateRunScript=True" Condition="'$(_CLRTestNeedsProjectToRun)' == 'True'"> <Output TaskParameter="TargetOutputs" PropertyName="_CLRTestToRunFileFullPath"/> </MSBuild> <PropertyGroup> <InputAssemblyName Condition="'$(CLRTestKind)' == 'RunOnly'">$([MSBuild]::MakeRelative($(OutputPath), $(_CLRTestToRunFileFullPath)))</InputAssemblyName> <InputAssemblyName Condition="'$(CLRTestKind)' == 'BuildAndRun'">$(AssemblyName).dll</InputAssemblyName> </PropertyGroup> </Target> <Target Name="GenerateExecutionScriptsInternal" Condition="$(_CLRTestNeedsToRun) or $(_CLRTestBuildsExecutable)" DependsOnTargets="FetchExternalProperties;Generate@(ExecutionScriptKind, 'ExecutionScript;Generate')ExecutionScript;" /> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/coreclr/debug/ee/amd64/gen_amd64InstrDecode/README.md
# Generating `amd64InstrDecode.h` ## TL;DR - What do I do? Process The following process was executed on an amd64 Linux host in this directory. ```bash # Create the program createOpcodes gcc createOpcodes.cpp -o createOpcodes # Execute the program to create opcodes.cpp ./createOpcodes > opcodes.cpp # Compile opcodes.cpp to opcodes gcc -g opcodes.cpp -o opcodes # Disassemble opcodes gdb opcodes -batch -ex "set disassembly-flavor intel" -ex "disass /r opcodes" > opcodes.intel # Parse disassembly and generate code cat opcodes.intel | dotnet run > ../amd64InstrDecode.h ``` ## Technical design `amd64InstrDecode.h`'s primary purpose is to provide a reliable and accurately mechanism to implement `Amd64 NativeWalker::DecodeInstructionForPatchSkip(..)`. This function needs to be able to decode an arbitrary `amd64` instruction. The decoder currently must be able to identify: - Whether the instruction includes an instruction pointer relative memory access - The location of the memory displacement within the instruction - The instruction length in bytes - The size of the memory operation in bytes To get this right is complicated, because the `amd64` instruction set is complicated. A high level view of the `amd64` instruction set can be seen by looking at `AMD64 Architecture Programmer’s Manual Volume 3: General-Purpose and System Instructions` `Section 1.1 Instruction Encoding Overview` `Figure 1-1. Instruction Encoding Syntax` The general behavior of each instruction can be modified by many of the bytes in the 1-15 byte instruction. This set of files generates a metadata table by extracting the data from sample instruction disassembly. The process entails - Generating a necessary set of instructions - Generating parsable disassembly for the instructions - Parsing the disassembly ### Generating a necessary set of instructions #### The necessary set - All instruction forms which use instruction pointer relative memory accesses. - All combinations of modifier bits which affect the instruction form - presence and/or size of the memory access - size or presence of immediates So with modrm.mod = 0, modrm.rm = 0x5 (instruction pointer relative memory access) we need all combinations of: - `opcodemap` - `opcode` - `modrm.reg` - `pp`, `W`, `L` - Some combinations of `vvvv` - Optional prefixes: `repe`, `repne`, `opSize` #### Padding We will iterate through all the necessary set. Many of these combinations will lead to invalid/undefined encodings. This will cause the disassembler to give up and mark the disassemble as bad. The disassemble will then resume trying to disassemble at the next boundary. To make sure the disassembler attempts to disassemble every instruction, we need to make sure the preceding instruction is always valid and terminates at our desired instruction boundary. Through examination of the `Primary` opcode map, it is observed that 0x50-0x5f are all 1 byte instructions. These become convenient padding. After each necessary instruction we insert enough padding bytes to fill the maximum instruction length and leave at least one additional one byte instruction. #### Fixed suffix Using a fixed suffix makes disassembly parsing simpler. After the modrm byte, the generated instructions always include a `postamble`, ```C++ const char* postamble = "0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,\n"; ``` This meets the padding consistency needs. #### Ordering As a convenience to the parser the encoded instructions are logically ordered. The ordering is generally, but can vary slightly depending on the needs of the particular opcode map: - map - opcode - pp & some prefixes - modrm.reg - W, L, vvvv This is to keep related instruction grouped together. #### Encoding the instructions The simplest way to get these instructions into an object file for disassembly is to place them into a C++ BYTE array. The file `createOpcodes.cpp` is the source for a program which will generate `opcodes.cpp` ```bash # Create the program createOpcodes gcc createOpcodes.cpp -o createOpcodes # Execute the program to create opcodes.cpp ./createOpcodes > opcodes.cpp ``` `opcodes.cpp` will now be a C++ source file with `uint8_t opcodes[]` initialized with our set of necessary instructions and padding. We need to compile this to an executable to prepare for disassembly. ```bash # Compile opcodes.cpp to opcodes gcc -g opcodes.cpp -o opcodes ``` ### Generating parsable disassembly In investigating the various disassembly formats, the `intel` disassembly format is superior to the `att` format. This is because the `intel` format clearly marks the instruction relative accesses and their sizes. For instance: - "BYTE PTR [rip+0x53525150]" - "WORD PTR [rip+0x53525150]" - "DWORD PTR [rip+0x53525150]" - "QWORD PTR [rip+0x53525150]" - "OWORD PTR [rip+0x53525150]" - "XMMWORD PTR [rip+0x53525150]" - "YMMWORD PTR [rip+0x53525150]" - "FWORD PTR [rip+0x53525150]" - "TBYTE PTR [rip+0x53525150]" Also it is important to have all the raw bytes in the disassembly. This allows accurately determining the instruction length. It also helps identifying which instructions are from our needed set. I happened to have used `gdb` as a disassembler. ```bash # Disassemble opcodes gdb opcodes -batch -ex "set disassembly-flavor intel" -ex "disass /r opcodes" > opcodes.intel ``` #### Alternative disassemblers It seems `objdump` could provide similar results. Untested, the parser may need to be modified for subtle differences. ```bash objdump -D -M intel -b --insn-width=15 -j .data opcodes ``` The lldb parser aborts parsing when it observes bad instruction. It might be usable with additional python scripts. Windows disassembler may also work. Not attempted. ### Parsing the disassembly ```bash # Parse disassembly and generate code cat opcodes.intel | dotnet run > ../amd64InstrDecode.h ``` #### Finding relevant disassembly lines We are not interested in all lines in the disassembly. The disassembler stray comments, recovery and our padding introduce lines we need to ignore. We filter out and ignore non-disassembly lines using a `Regex` for a disassembly line. We expect the generated instruction samples to be in a group. The first instruction in the group is the only one we are interested in. This is the one we are interested in. The group is terminated by a pair of instructions. The first terminal instruction must have `0x58` as the last byte in it encoding. The final terminal instruction must be a `0x59\tpop`. We continue parsing the first line of each group. #### Ignoring bad encodings Many encodings are not valid. For `gdb`, these instructions are marked `(bad)`. We filter and ignore these. #### Parsing the disassambly for each instruction sample For each sample, we need to calculate the important properties: - mnemonic - raw encoding - disassembly (for debug) - Encoding - map - opcode position - Encoding Flags - pp, W, L, prefix and encoding flags - `SuffixFlags` - presence of instruction relative accesses - size of operation - position in the list of operands - number of immediate bytes ##### Supplementing the disassembler In a few cases it was observed the disassembly of some memory operations did not include a size. These were manually researched. For the ones with reasonable sizes, these were added to a table to manually override these unknown sizes. #### `opCodeExt` To facilitate identifying sets of instructions, the creates an `opCodeExt`. For the `Primary` map this is simply the encoded opcode from the instruction shifted left by 4 bits. For the 3D Now `NOW3D` map this is simply the encoded immediate from the instruction shifted left by 4 bits. For the `Secondary` `F38`, and `F39` maps this is the encoded opcode from the instruction shifted left by 4 bits orred with a synthetic `pp`. The synthetic `pp` is constructed to match the rules of `Table 1-22. VEX/XOP.pp Encoding` from the `AMD64 Architecture Programmer’s Manual Volume 3: General-Purpose and System Instructions`. For the case where the opSize 0x66 prefix is present with a `rep*` prefix, the `rep*` prefix is used to encode `pp`. For the `VEX*` and `XOP*` maps this is the encoded opcode from the instruction shifted left by 4 bits orred with `pp`. #### Identifying sets of instructions For most instructions, the opCodeExt will uniquely identify the instruction. For many instructions, `modrm.reg` is used to uniquely identify the instruction. These instruction typically change mnemonic and behavior as `modrm.reg` changes. These become problematic, when the form of these instructions vary. For a few other instructions the `L`, `W`, `vvvv` value may the instruction change behavior. Usually these do not change mnemonic. The set of instructions is therefore usually grouped by the opcode map and `opCodeExt` generated above. For these a change in `opCodeExt` or `map` will start a new group. For select problematic groups of `modrm.reg` sensitive instructions, a change in modrm.reg will start a new group. #### For each set of instructions - Calculate the `intersection` and `union` of the `SuffixFlags` for the set. - The flags in the `intersection` are common to all instructions in the set. - The ones in the `union`, but not in the `intersection` vary within the set based on the encoding flags. These are the `sometimesFlags` - Determine the rules for the `sometimesFlags`. For each combination of `sometimesFlags`, check each rule by calling `TestHypothesis`. This determines if the rule corresponds to the set of observations. Encode the rule as a string. Add the rule to the set of all observed rules. Add the set's rule with comment to a dictionary. #### Generating the C++ code At this point generating the code is rather simple. Iterate through the set of rules to create an enumeration of `InstrForm`. For each map iterate through the dictionary, filling missing instructions with an appropriate pattern for undefined instructions. ##### Encoding The design uses a simple fully populated direct look up table to provide a nice simple means of looking up. This direct map approach is expected to consume ~10K bytes. Other approaches like a sparse list may reduce total memory usage. The added complexity did not seem worth it. ## Benefits This approach is intended to reduce the human error introduced by manually parsing and encoding the various instruction forms from their respective descriptions. ## Limitations The approach of using a single object file as the source of disassembly samples, is restricted to a max compilation/link unit size. Early drafts were generating more instructions, and couldn't be compiled. However, there is no restriction that all the samples must come from single executable. These could easily be separated by opcode map... ## Risks ### New instruction sets This design is for existing instruction sets. New instruction sets will require more work. Further this methodology uses the disassembler to generate the tables. Until a reasonably featured disassembler is created, the new instruction set can not be supported by this methodology. The previous methodology of manually encoding these new instruction set would still be possible.... ### Disassembler errors This design presumes the disassembler is correct. The specific version of the disassembler may have disassembly bugs. Using newer disassemblers would mitigate this to some extent. ### Bugs - Inadequate samples. Are there other bits which modify instruction behavior which we missed? - Parser/Table generator implementation bugs. Does the parser do what it was intended to do? ## Reasons to regenerate the file ### Disassembler error discovered Add a patch to the parser to workaround the bug and regenerate the table ### Newer disassembler available Regenerate and compare. ### New debugger feature requires more metadata Add new feature code, regenerate
# Generating `amd64InstrDecode.h` ## TL;DR - What do I do? Process The following process was executed on an amd64 Linux host in this directory. ```bash # Create the program createOpcodes gcc createOpcodes.cpp -o createOpcodes # Execute the program to create opcodes.cpp ./createOpcodes > opcodes.cpp # Compile opcodes.cpp to opcodes gcc -g opcodes.cpp -o opcodes # Disassemble opcodes gdb opcodes -batch -ex "set disassembly-flavor intel" -ex "disass /r opcodes" > opcodes.intel # Parse disassembly and generate code cat opcodes.intel | dotnet run > ../amd64InstrDecode.h ``` ## Technical design `amd64InstrDecode.h`'s primary purpose is to provide a reliable and accurately mechanism to implement `Amd64 NativeWalker::DecodeInstructionForPatchSkip(..)`. This function needs to be able to decode an arbitrary `amd64` instruction. The decoder currently must be able to identify: - Whether the instruction includes an instruction pointer relative memory access - The location of the memory displacement within the instruction - The instruction length in bytes - The size of the memory operation in bytes To get this right is complicated, because the `amd64` instruction set is complicated. A high level view of the `amd64` instruction set can be seen by looking at `AMD64 Architecture Programmer’s Manual Volume 3: General-Purpose and System Instructions` `Section 1.1 Instruction Encoding Overview` `Figure 1-1. Instruction Encoding Syntax` The general behavior of each instruction can be modified by many of the bytes in the 1-15 byte instruction. This set of files generates a metadata table by extracting the data from sample instruction disassembly. The process entails - Generating a necessary set of instructions - Generating parsable disassembly for the instructions - Parsing the disassembly ### Generating a necessary set of instructions #### The necessary set - All instruction forms which use instruction pointer relative memory accesses. - All combinations of modifier bits which affect the instruction form - presence and/or size of the memory access - size or presence of immediates So with modrm.mod = 0, modrm.rm = 0x5 (instruction pointer relative memory access) we need all combinations of: - `opcodemap` - `opcode` - `modrm.reg` - `pp`, `W`, `L` - Some combinations of `vvvv` - Optional prefixes: `repe`, `repne`, `opSize` #### Padding We will iterate through all the necessary set. Many of these combinations will lead to invalid/undefined encodings. This will cause the disassembler to give up and mark the disassemble as bad. The disassemble will then resume trying to disassemble at the next boundary. To make sure the disassembler attempts to disassemble every instruction, we need to make sure the preceding instruction is always valid and terminates at our desired instruction boundary. Through examination of the `Primary` opcode map, it is observed that 0x50-0x5f are all 1 byte instructions. These become convenient padding. After each necessary instruction we insert enough padding bytes to fill the maximum instruction length and leave at least one additional one byte instruction. #### Fixed suffix Using a fixed suffix makes disassembly parsing simpler. After the modrm byte, the generated instructions always include a `postamble`, ```C++ const char* postamble = "0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,\n"; ``` This meets the padding consistency needs. #### Ordering As a convenience to the parser the encoded instructions are logically ordered. The ordering is generally, but can vary slightly depending on the needs of the particular opcode map: - map - opcode - pp & some prefixes - modrm.reg - W, L, vvvv This is to keep related instruction grouped together. #### Encoding the instructions The simplest way to get these instructions into an object file for disassembly is to place them into a C++ BYTE array. The file `createOpcodes.cpp` is the source for a program which will generate `opcodes.cpp` ```bash # Create the program createOpcodes gcc createOpcodes.cpp -o createOpcodes # Execute the program to create opcodes.cpp ./createOpcodes > opcodes.cpp ``` `opcodes.cpp` will now be a C++ source file with `uint8_t opcodes[]` initialized with our set of necessary instructions and padding. We need to compile this to an executable to prepare for disassembly. ```bash # Compile opcodes.cpp to opcodes gcc -g opcodes.cpp -o opcodes ``` ### Generating parsable disassembly In investigating the various disassembly formats, the `intel` disassembly format is superior to the `att` format. This is because the `intel` format clearly marks the instruction relative accesses and their sizes. For instance: - "BYTE PTR [rip+0x53525150]" - "WORD PTR [rip+0x53525150]" - "DWORD PTR [rip+0x53525150]" - "QWORD PTR [rip+0x53525150]" - "OWORD PTR [rip+0x53525150]" - "XMMWORD PTR [rip+0x53525150]" - "YMMWORD PTR [rip+0x53525150]" - "FWORD PTR [rip+0x53525150]" - "TBYTE PTR [rip+0x53525150]" Also it is important to have all the raw bytes in the disassembly. This allows accurately determining the instruction length. It also helps identifying which instructions are from our needed set. I happened to have used `gdb` as a disassembler. ```bash # Disassemble opcodes gdb opcodes -batch -ex "set disassembly-flavor intel" -ex "disass /r opcodes" > opcodes.intel ``` #### Alternative disassemblers It seems `objdump` could provide similar results. Untested, the parser may need to be modified for subtle differences. ```bash objdump -D -M intel -b --insn-width=15 -j .data opcodes ``` The lldb parser aborts parsing when it observes bad instruction. It might be usable with additional python scripts. Windows disassembler may also work. Not attempted. ### Parsing the disassembly ```bash # Parse disassembly and generate code cat opcodes.intel | dotnet run > ../amd64InstrDecode.h ``` #### Finding relevant disassembly lines We are not interested in all lines in the disassembly. The disassembler stray comments, recovery and our padding introduce lines we need to ignore. We filter out and ignore non-disassembly lines using a `Regex` for a disassembly line. We expect the generated instruction samples to be in a group. The first instruction in the group is the only one we are interested in. This is the one we are interested in. The group is terminated by a pair of instructions. The first terminal instruction must have `0x58` as the last byte in it encoding. The final terminal instruction must be a `0x59\tpop`. We continue parsing the first line of each group. #### Ignoring bad encodings Many encodings are not valid. For `gdb`, these instructions are marked `(bad)`. We filter and ignore these. #### Parsing the disassambly for each instruction sample For each sample, we need to calculate the important properties: - mnemonic - raw encoding - disassembly (for debug) - Encoding - map - opcode position - Encoding Flags - pp, W, L, prefix and encoding flags - `SuffixFlags` - presence of instruction relative accesses - size of operation - position in the list of operands - number of immediate bytes ##### Supplementing the disassembler In a few cases it was observed the disassembly of some memory operations did not include a size. These were manually researched. For the ones with reasonable sizes, these were added to a table to manually override these unknown sizes. #### `opCodeExt` To facilitate identifying sets of instructions, the creates an `opCodeExt`. For the `Primary` map this is simply the encoded opcode from the instruction shifted left by 4 bits. For the 3D Now `NOW3D` map this is simply the encoded immediate from the instruction shifted left by 4 bits. For the `Secondary` `F38`, and `F39` maps this is the encoded opcode from the instruction shifted left by 4 bits orred with a synthetic `pp`. The synthetic `pp` is constructed to match the rules of `Table 1-22. VEX/XOP.pp Encoding` from the `AMD64 Architecture Programmer’s Manual Volume 3: General-Purpose and System Instructions`. For the case where the opSize 0x66 prefix is present with a `rep*` prefix, the `rep*` prefix is used to encode `pp`. For the `VEX*` and `XOP*` maps this is the encoded opcode from the instruction shifted left by 4 bits orred with `pp`. #### Identifying sets of instructions For most instructions, the opCodeExt will uniquely identify the instruction. For many instructions, `modrm.reg` is used to uniquely identify the instruction. These instruction typically change mnemonic and behavior as `modrm.reg` changes. These become problematic, when the form of these instructions vary. For a few other instructions the `L`, `W`, `vvvv` value may the instruction change behavior. Usually these do not change mnemonic. The set of instructions is therefore usually grouped by the opcode map and `opCodeExt` generated above. For these a change in `opCodeExt` or `map` will start a new group. For select problematic groups of `modrm.reg` sensitive instructions, a change in modrm.reg will start a new group. #### For each set of instructions - Calculate the `intersection` and `union` of the `SuffixFlags` for the set. - The flags in the `intersection` are common to all instructions in the set. - The ones in the `union`, but not in the `intersection` vary within the set based on the encoding flags. These are the `sometimesFlags` - Determine the rules for the `sometimesFlags`. For each combination of `sometimesFlags`, check each rule by calling `TestHypothesis`. This determines if the rule corresponds to the set of observations. Encode the rule as a string. Add the rule to the set of all observed rules. Add the set's rule with comment to a dictionary. #### Generating the C++ code At this point generating the code is rather simple. Iterate through the set of rules to create an enumeration of `InstrForm`. For each map iterate through the dictionary, filling missing instructions with an appropriate pattern for undefined instructions. ##### Encoding The design uses a simple fully populated direct look up table to provide a nice simple means of looking up. This direct map approach is expected to consume ~10K bytes. Other approaches like a sparse list may reduce total memory usage. The added complexity did not seem worth it. ## Benefits This approach is intended to reduce the human error introduced by manually parsing and encoding the various instruction forms from their respective descriptions. ## Limitations The approach of using a single object file as the source of disassembly samples, is restricted to a max compilation/link unit size. Early drafts were generating more instructions, and couldn't be compiled. However, there is no restriction that all the samples must come from single executable. These could easily be separated by opcode map... ## Risks ### New instruction sets This design is for existing instruction sets. New instruction sets will require more work. Further this methodology uses the disassembler to generate the tables. Until a reasonably featured disassembler is created, the new instruction set can not be supported by this methodology. The previous methodology of manually encoding these new instruction set would still be possible.... ### Disassembler errors This design presumes the disassembler is correct. The specific version of the disassembler may have disassembly bugs. Using newer disassemblers would mitigate this to some extent. ### Bugs - Inadequate samples. Are there other bits which modify instruction behavior which we missed? - Parser/Table generator implementation bugs. Does the parser do what it was intended to do? ## Reasons to regenerate the file ### Disassembler error discovered Add a patch to the parser to workaround the bug and regenerate the table ### Newer disassembler available Regenerate and compare. ### New debugger feature requires more metadata Add new feature code, regenerate
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/shims/ref/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <!-- Allow shim ref projects to reference source projects. --> <SkipValidateReferenceAssemblyProjectReferences>true</SkipValidateReferenceAssemblyProjectReferences> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <!-- Allow shim ref projects to reference source projects. --> <SkipValidateReferenceAssemblyProjectReferences>true</SkipValidateReferenceAssemblyProjectReferences> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/buildTransitive/Microsoft.Extensions.Configuration.UserSecrets.targets
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <GenerateUserSecretsAttribute Condition="'$(GenerateUserSecretsAttribute)'==''">true</GenerateUserSecretsAttribute> </PropertyGroup> <ItemGroup Condition=" '$(UserSecretsId)' != '' AND '$(GenerateUserSecretsAttribute)' != 'false' "> <AssemblyAttribute Include="Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute"> <_Parameter1>$(UserSecretsId.Trim())</_Parameter1> </AssemblyAttribute> </ItemGroup> </Project>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <GenerateUserSecretsAttribute Condition="'$(GenerateUserSecretsAttribute)'==''">true</GenerateUserSecretsAttribute> </PropertyGroup> <ItemGroup Condition=" '$(UserSecretsId)' != '' AND '$(GenerateUserSecretsAttribute)' != 'false' "> <AssemblyAttribute Include="Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute"> <_Parameter1>$(UserSecretsId.Trim())</_Parameter1> </AssemblyAttribute> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/FunctionalTests/WebAssembly/Directory.Build.props
<Project> <PropertyGroup> <!-- These need to be set here because the root Directory.Build.props sets up the intermediate path early --> <Configuration>Release</Configuration> <OutputType>Exe</OutputType> </PropertyGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props, '$(MSBuildThisFileDirectory)..'))" /> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <OutputPath>$(RepoRoot)artifacts\bin\$(MSBuildProjectName)</OutputPath> <_InTreeEmSdk>$(MSBuildThisFileDirectory)..\..\..\mono\wasm\emsdk</_InTreeEmSdk> <EMSDK_PATH Condition="'$(EMSDK_PATH)' == '' and Exists($(_InTreeEmSdk))">$(_InTreeEmSdk)</EMSDK_PATH> </PropertyGroup> </Project>
<Project> <PropertyGroup> <!-- These need to be set here because the root Directory.Build.props sets up the intermediate path early --> <Configuration>Release</Configuration> <OutputType>Exe</OutputType> </PropertyGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props, '$(MSBuildThisFileDirectory)..'))" /> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <OutputPath>$(RepoRoot)artifacts\bin\$(MSBuildProjectName)</OutputPath> <_InTreeEmSdk>$(MSBuildThisFileDirectory)..\..\..\mono\wasm\emsdk</_InTreeEmSdk> <EMSDK_PATH Condition="'$(EMSDK_PATH)' == '' and Exists($(_InTreeEmSdk))">$(_InTreeEmSdk)</EMSDK_PATH> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Security.Cryptography.Csp/tests/TrimmingTests/System.Security.Cryptography.Csp.TrimmingTests.proj
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <PropertyGroup> <SkipOnTestRuntimes>browser-wasm</SkipOnTestRuntimes> <!-- Justification: System.Security.Cryptography.DeriveBytes..ctor() throws PNSE on wasm --> </PropertyGroup> <ItemGroup> <TestConsoleAppSourceFiles Include="PasswordDeriveBytesTest.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <PropertyGroup> <SkipOnTestRuntimes>browser-wasm</SkipOnTestRuntimes> <!-- Justification: System.Security.Cryptography.DeriveBytes..ctor() throws PNSE on wasm --> </PropertyGroup> <ItemGroup> <TestConsoleAppSourceFiles Include="PasswordDeriveBytesTest.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/coreclr/nativeaot/docs/README.md
# Using Native AOT - [Limitations](limitations.md) - [Compiling applications](compiling.md) - [Debugging applications](debugging.md) - [Optimizing applications](optimizing.md) - [Reflection In AOT](reflection-in-aot-mode.md) - [Managed/Native Interop in AOT](interop.md) - [Troubleshooting](troubleshooting.md) - [RD.xml Documentation](rd-xml-format.md)
# Using Native AOT - [Limitations](limitations.md) - [Compiling applications](compiling.md) - [Debugging applications](debugging.md) - [Optimizing applications](optimizing.md) - [Reflection In AOT](reflection-in-aot-mode.md) - [Managed/Native Interop in AOT](interop.md) - [Troubleshooting](troubleshooting.md) - [RD.xml Documentation](rd-xml-format.md)
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./eng/testing/debug-dump-template.md
# Get the Helix payload [Runfo](https://github.com/jaredpar/runfo/tree/master/runfo#runfo) helps get information about helix test runs and azure devops builds. We will use it to download the payload and symbols (recommended version 0.6.4 or later): ```sh dotnet tool install --global runfo dotnet tool update --global runfo ``` If prompted, open a new command prompt to pick up the updated PATH. Windows: ```cmd :: assumes %WOUTDIR% does not exist runfo get-helix-payload -j %JOBID% -w %WORKITEM% -o %WOUTDIR% ``` Linux and macOS: ```sh # assumes %LOUTDIR% does not exist runfo get-helix-payload -j %JOBID% -w %WORKITEM% -o %LOUTDIR% ``` Any dump files published by helix will be downloaded. > NOTE: if the helix job is an internal job, you need to pass down a [helix authentication token](https://helix.dot.net/Account/Tokens) using the `--helix-token` argument. Now extract the files: Windows: ```cmd for /f %i in ('dir /s/b %WOUTDIR%\*zip') do tar -xf %i -C %WOUTDIR% ``` Linux and macOS ```sh # obtain `unzip` if necessary; eg `sudo apt-get install unzip` or `sudo dnf install unzip` find %LOUTDIR% -name '*zip' -exec unzip -d %LOUTDIR% {} \; ``` # If the dump is for NativeAOT Rest of the document discusses how to debug the dump using the SOS extension and DAC because native debuggers are lost without the extension. The SOS extension is not necessary (and doesn't work) for NativeAOT. NativeAOT debugs like a native app. Open the crash dump in your debugger of choice, including Visual Studio. To interpret the dump you'll need symbols - the symbols are in the ZIP file - a separate PDB file on Windows, and the executable itself outside Windows. You can read the rest of the document for information purposes (there is useful info on e.g. how to set up symbol path), but you can stop reading now if you already have experience with native debugging. # Install SOS debugging extension Now use the [dotnet-sos global tool](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-sos) to install the SOS debugging extension. ```cmd dotnet tool install --global dotnet-sos dotnet tool update --global dotnet-sos ``` If prompted, open a new command prompt to pick up the updated PATH. ```cmd :: Install only one: the one matching your dump dotnet sos install --architecture Arm dotnet sos install --architecture Arm64 dotnet sos install --architecture x86 dotnet sos install --architecture x64 ``` # Now choose a section below based on your OS. ## If it's a Windows dump on Windows... ## ... and you want to debug with WinDbg Install or update WinDbg if necessary ([external](https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools), [internal](https://osgwiki.com/wiki/Installing_WinDbg)). If you don't have a recent WinDbg you may have to do `.update sos`. Open WinDbg and open the dump with `File>Open Dump`. ``` <win-path-to-dump> ``` ``` !setclrpath %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION% .sympath+ %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION% ``` Now you can use regular SOS commands like `!dumpstack`, `!pe`, etc. ## ... and you want to debug with Visual Studio Currently this is not possible because mscordbi.dll is not signed. ## ... and you want to debug with dotnet-dump Install the [dotnet-dump global tool](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump). ```cmd dotnet tool install --global dotnet-dump dotnet tool update --global dotnet-dump ``` If prompted, open a new command prompt to pick up the updated PATH. ```cmd dotnet-dump analyze ^ <win-path-to-dump> ^ --command "setclrpath %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION%" ^ "setsymbolserver -directory %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION%" ``` Now you can use regular SOS commands like `dumpstack`, `pe`, etc. If you are debugging a 32 bit dump using 64 bit dotnet, you will get an error `SOS does not support the current target architecture`. In that case replace dotnet-dump with the 32 bit version: ```cmd dotnet tool uninstall --global dotnet-dump "C:\Program Files (x86)\dotnet\dotnet.exe" tool install --global dotnet-dump ``` --- ## If it's a Linux dump on Windows... Download the [Cross DAC Binaries](https://dev.azure.com/dnceng/public/_apis/build/builds/%BUILDID%/artifacts?artifactName=CoreCLRCrossDacArtifacts&api-version=6.0&%24format=zip), open it and choose the flavor that matches the dump you are to debug, and copy those files to `%WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION%`. Now you can debug with WinDbg or `dotnet-dump` as if it was a Windows dump. See above. --- ## If it's a Linux dump on Linux... ## ... and you want to debug with LLDB Install or update LLDB if necessary ([instructions here](https://github.com/dotnet/diagnostics/blob/master/documentation/lldb/linux-instructions.md)) Load the dump: ```sh lldb --core <lin-path-to-dump> \ %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%/dotnet \ -o "setclrpath %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" \ -o "setsymbolserver -directory %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" ``` If you want to load native symbols ```gdb loadsymbols ``` ## ... and you want to debug with dotnet-dump Install the [dotnet-dump global tool](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump). ```sh dotnet tool install --global dotnet-dump dotnet tool update --global dotnet-dump ``` If prompted, open a new command prompt to pick up the updated PATH. ```sh dotnet-dump analyze \ <lin-path-to-dump> \ --command "setclrpath %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" \ "setsymbolserver -directory %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" ``` --- ## If it's a macOS dump Instructions for debugging dumps on macOS are essentially the same as [Linux](#If-it's-a-Linux-dump-on-Linux...) with one exception: `dotnet-dump` cannot analyze macOS system dumps yet: you must use `lldb` for those. As of .NET 6, createdump on macOS will start generating native Mach-O core files. dotnet-dump and ClrMD are still being worked on to handle these dumps. --- # Other Helpful Information * [How to debug a Linux core dump with SOS](https://github.com/dotnet/diagnostics/blob/master/documentation/debugging-coredump.md)
# Get the Helix payload [Runfo](https://github.com/jaredpar/runfo/tree/master/runfo#runfo) helps get information about helix test runs and azure devops builds. We will use it to download the payload and symbols (recommended version 0.6.4 or later): ```sh dotnet tool install --global runfo dotnet tool update --global runfo ``` If prompted, open a new command prompt to pick up the updated PATH. Windows: ```cmd :: assumes %WOUTDIR% does not exist runfo get-helix-payload -j %JOBID% -w %WORKITEM% -o %WOUTDIR% ``` Linux and macOS: ```sh # assumes %LOUTDIR% does not exist runfo get-helix-payload -j %JOBID% -w %WORKITEM% -o %LOUTDIR% ``` Any dump files published by helix will be downloaded. > NOTE: if the helix job is an internal job, you need to pass down a [helix authentication token](https://helix.dot.net/Account/Tokens) using the `--helix-token` argument. Now extract the files: Windows: ```cmd for /f %i in ('dir /s/b %WOUTDIR%\*zip') do tar -xf %i -C %WOUTDIR% ``` Linux and macOS ```sh # obtain `unzip` if necessary; eg `sudo apt-get install unzip` or `sudo dnf install unzip` find %LOUTDIR% -name '*zip' -exec unzip -d %LOUTDIR% {} \; ``` # If the dump is for NativeAOT Rest of the document discusses how to debug the dump using the SOS extension and DAC because native debuggers are lost without the extension. The SOS extension is not necessary (and doesn't work) for NativeAOT. NativeAOT debugs like a native app. Open the crash dump in your debugger of choice, including Visual Studio. To interpret the dump you'll need symbols - the symbols are in the ZIP file - a separate PDB file on Windows, and the executable itself outside Windows. You can read the rest of the document for information purposes (there is useful info on e.g. how to set up symbol path), but you can stop reading now if you already have experience with native debugging. # Install SOS debugging extension Now use the [dotnet-sos global tool](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-sos) to install the SOS debugging extension. ```cmd dotnet tool install --global dotnet-sos dotnet tool update --global dotnet-sos ``` If prompted, open a new command prompt to pick up the updated PATH. ```cmd :: Install only one: the one matching your dump dotnet sos install --architecture Arm dotnet sos install --architecture Arm64 dotnet sos install --architecture x86 dotnet sos install --architecture x64 ``` # Now choose a section below based on your OS. ## If it's a Windows dump on Windows... ## ... and you want to debug with WinDbg Install or update WinDbg if necessary ([external](https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools), [internal](https://osgwiki.com/wiki/Installing_WinDbg)). If you don't have a recent WinDbg you may have to do `.update sos`. Open WinDbg and open the dump with `File>Open Dump`. ``` <win-path-to-dump> ``` ``` !setclrpath %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION% .sympath+ %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION% ``` Now you can use regular SOS commands like `!dumpstack`, `!pe`, etc. ## ... and you want to debug with Visual Studio Currently this is not possible because mscordbi.dll is not signed. ## ... and you want to debug with dotnet-dump Install the [dotnet-dump global tool](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump). ```cmd dotnet tool install --global dotnet-dump dotnet tool update --global dotnet-dump ``` If prompted, open a new command prompt to pick up the updated PATH. ```cmd dotnet-dump analyze ^ <win-path-to-dump> ^ --command "setclrpath %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION%" ^ "setsymbolserver -directory %WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION%" ``` Now you can use regular SOS commands like `dumpstack`, `pe`, etc. If you are debugging a 32 bit dump using 64 bit dotnet, you will get an error `SOS does not support the current target architecture`. In that case replace dotnet-dump with the 32 bit version: ```cmd dotnet tool uninstall --global dotnet-dump "C:\Program Files (x86)\dotnet\dotnet.exe" tool install --global dotnet-dump ``` --- ## If it's a Linux dump on Windows... Download the [Cross DAC Binaries](https://dev.azure.com/dnceng/public/_apis/build/builds/%BUILDID%/artifacts?artifactName=CoreCLRCrossDacArtifacts&api-version=6.0&%24format=zip), open it and choose the flavor that matches the dump you are to debug, and copy those files to `%WOUTDIR%\shared\Microsoft.NETCore.App\%PRODUCTVERSION%`. Now you can debug with WinDbg or `dotnet-dump` as if it was a Windows dump. See above. --- ## If it's a Linux dump on Linux... ## ... and you want to debug with LLDB Install or update LLDB if necessary ([instructions here](https://github.com/dotnet/diagnostics/blob/master/documentation/lldb/linux-instructions.md)) Load the dump: ```sh lldb --core <lin-path-to-dump> \ %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%/dotnet \ -o "setclrpath %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" \ -o "setsymbolserver -directory %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" ``` If you want to load native symbols ```gdb loadsymbols ``` ## ... and you want to debug with dotnet-dump Install the [dotnet-dump global tool](https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump). ```sh dotnet tool install --global dotnet-dump dotnet tool update --global dotnet-dump ``` If prompted, open a new command prompt to pick up the updated PATH. ```sh dotnet-dump analyze \ <lin-path-to-dump> \ --command "setclrpath %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" \ "setsymbolserver -directory %LOUTDIR%/shared/Microsoft.NETCore.App/%PRODUCTVERSION%" ``` --- ## If it's a macOS dump Instructions for debugging dumps on macOS are essentially the same as [Linux](#If-it's-a-Linux-dump-on-Linux...) with one exception: `dotnet-dump` cannot analyze macOS system dumps yet: you must use `lldb` for those. As of .NET 6, createdump on macOS will start generating native Mach-O core files. dotnet-dump and ClrMD are still being worked on to handle these dumps. --- # Other Helpful Information * [How to debug a Linux core dump with SOS](https://github.com/dotnet/diagnostics/blob/master/documentation/debugging-coredump.md)
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Runtime.InteropServices/gen/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <EnableLibraryImportGenerator>false</EnableLibraryImportGenerator> <EnableDefaultItems>true</EnableDefaultItems> <CLSCompliant>false</CLSCompliant> <!-- Localization --> <UsingToolXliff>true</UsingToolXliff> <EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <EnableLibraryImportGenerator>false</EnableLibraryImportGenerator> <EnableDefaultItems>true</EnableDefaultItems> <CLSCompliant>false</CLSCompliant> <!-- Localization --> <UsingToolXliff>true</UsingToolXliff> <EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/Microsoft.Extensions.Hosting.WindowsServices/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <PackageTags>hosting</PackageTags> <IncludePlatformAttributes>true</IncludePlatformAttributes> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <PackageTags>hosting</PackageTags> <IncludePlatformAttributes>true</IncludePlatformAttributes> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Reflection.Emit.ILGeneration/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./docs/workflow/building/libraries/cross-building.md
Cross Compilation for ARM on Linux ================================== It is possible to build CoreFx on Linux for arm, armel, or arm64 by cross compiling. It is very similar to the cross compilation procedure of CoreCLR. Requirements ------------ You need a Debian based host, and the following packages need to be installed: $ sudo apt-get install qemu qemu-user-static binfmt-support debootstrap In addition, to cross compile CoreFX, the binutils for the target are required. So for arm you need: $ sudo apt-get install binutils-arm-linux-gnueabihf for armel: $ sudo apt-get install binutils-arm-linux-gnueabi and for arm64 you need: $ sudo apt-get install binutils-aarch64-linux-gnu Generating the rootfs --------------------- The `eng/common/cross/build-rootfs.sh` script can be used to download the files needed for cross compilation. It will generate an Ubuntu 16.04 rootfs as this is what CoreFX targets. Usage: ./eng/common/cross/build-rootfs.sh [BuildArch] [LinuxCodeName] [lldbx.y] [--skipunmount] --rootfsdir <directory>] BuildArch can be: arm, armel, arm64, x86 LinuxCodeName - optional, Code name for Linux, can be: trusty, xenial(default), zesty, bionic, alpine. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen. lldbx.y - optional, LLDB version, can be: lldb3.9(default), lldb4.0, lldb5.0, lldb6.0 no-lldb. Ignored for alpine The `build-rootfs.sh` script must be run as root, as it has to make some symlinks to the system. It will, by default, generate the rootfs in `cross/rootfs/<BuildArch>` however this can be changed by setting the `ROOTFS_DIR` environment variable or by using --rootfsdir. For example, to generate an arm rootfs: $ sudo ./eng/common/cross/build-rootfs.sh arm and if you wanted to generate the rootfs elsewhere: $ sudo ./build-rootfs.sh arm --rootfsdir /mnt/corefx-cross/arm Cross compiling for native CoreFX --------------------------------- Once the rootfs has been generated, it will be possible to cross compile CoreFX. If `ROOTFS_DIR` was set when generating the rootfs, then it must also be set when running `build.sh`. So, without `ROOTFS_DIR`: $ ./src/Native/build-native.sh debug arm verbose cross And with: $ ROOTFS_DIR=/mnt/corefx-cross/arm ./src/Native/build-native.sh debug arm verbose cross As usual the generated binaries will be found in `artifacts/bin/TargetOS.BuildArch.BuildType/native` as following: $ ls -al ./artifacts/bin/Linux.arm.Debug/native total 988 drwxrwxr-x 2 lgs lgs 4096 3 6 18:33 . drwxrwxr-x 3 lgs lgs 4096 3 6 18:33 .. -rw-r--r-- 1 lgs lgs 19797 3 6 18:33 System.IO.Compression.Native.so -rw-r--r-- 1 lgs lgs 428232 3 6 18:33 System.Native.a -rw-r--r-- 1 lgs lgs 228279 3 6 18:33 System.Native.so -rw-r--r-- 1 lgs lgs 53089 3 6 18:33 System.Net.Http.Native.so -rw-r--r-- 1 lgs lgs 266720 3 6 18:33 System.Security.Cryptography.Native.so $ file ./artifacts/bin/Linux.arm.Debug/native/System.Native.so ./bin/Linux.arm.Debug/native/System.Native.so: ELF 32-bit LSB shared object, ARM, EABI5 version 1 (SYSV), dynamically linked, BuildID[sha1]=fac50f1bd657c1759f0ad6cf5951511ddf252e67, not stripped Compiling for managed CoreFX ============================ The managed components of CoreFX are architecture-independent and thus do not require a special build for arm, armel or arm64. Many of the managed binaries are also OS-independent, e.g. System.Linq.dll, while some are OS-specific, e.g. System.IO.FileSystem.dll, with different builds for Windows and Linux. $ ROOTFS_DIR=/mnt/corefx-cross/arm ./build.sh --arch arm You can also build just managed code with: $ ./build.sh --arch arm /p:BuildNative=false The output is at `artifacts/bin/[BuildSettings]` where `BuildSettings` looks something like `net5.0-<TargetOS>-Debug-<Architecture>`. Ex: `artifacts/bin/net5.0-Linux-Debug-x64`. For more details on the build configurations see [project-guidelines](/docs/coding-guidelines/project-guidelines.md) Building corefx for Linux ARM Emulator ======================================= It is possible to build corefx binaries (native and managed) for the Linux ARM Emulator (latest version provided here: [#5394](https://github.com/dotnet/runtime/issues/5394)). The `scripts/arm32_ci_script.sh` script does this. The following instructions assume that: * You have set up the extracted emulator at `/opt/linux-arm-emulator` (such that `/opt/linux-arm-emulator/platform/rootfs-t30.ext4` exists) * The mount path for the emulator rootfs is `/opt/linux-arm-emulator-root` (change this path if you have a working directory at this path). All the following instructions are for the Release mode. Change the commands and files accordingly for the Debug mode. To just build the native and managed corefx binaries for the Linux ARM Emulator, run the following command: ``` prajwal@ubuntu ~/corefx $ ./scripts/arm32_ci_script.sh \ --emulatorPath=/opt/linux-arm-emulator \ --mountPath=/opt/linux-arm-emulator-root \ --buildConfig=Release ``` The Linux ARM Emulator is based on the soft floating point and thus the native binaries are generated for the armel architecture. The corefx binaries generated by the above command can be found at `~/corefx/artifacts/bin/Linux.armel.Release`, `~/corefx/artifacts/bin/Linux.AnyCPU.Release`, `~/corefx/artifacts/bin/Unix.AnyCPU.Release`, and `~/corefx/artifacts/bin/AnyOS.AnyCPU.Release`. Build corefx for a new architecture =================================== When building for a new architecture you will need to build the native pieces separate from the managed pieces in order to correctly boot strap the native runtime. Instead of calling build.sh directly you should instead split the calls like such: Example building for armel ``` src/Native/build-native.sh armel --> Output goes to artifacts/bin/runtime/net5.0-Linux-Debug-armel build /p:TargetArchitecture=x64 /p:BuildNative=false --> Output goes to artifacts/bin/runtime/net5.0-Linux-Debug-x64 ``` The reason you need to build the managed portion for x64 is because it depends on runtime packages for the new architecture which don't exist yet so we use another existing architecture such as x64 as a proxy for building the managed binaries. Similar if you want to try and run tests you will have to copy the managed assemblies from the proxy directory (i.e. `net5.0-Linux-Debug-x64`) to the new architecture directory (i.e `net5.0-Linux-Debug-armel`) and run code via another host such as corerun because dotnet is at a higher level and most likely doesn't exist for the new architecture yet. Once all the necessary builds are setup and packages are published the splitting of the build and manual creation of the runtime should no longer be necessary.
Cross Compilation for ARM on Linux ================================== It is possible to build CoreFx on Linux for arm, armel, or arm64 by cross compiling. It is very similar to the cross compilation procedure of CoreCLR. Requirements ------------ You need a Debian based host, and the following packages need to be installed: $ sudo apt-get install qemu qemu-user-static binfmt-support debootstrap In addition, to cross compile CoreFX, the binutils for the target are required. So for arm you need: $ sudo apt-get install binutils-arm-linux-gnueabihf for armel: $ sudo apt-get install binutils-arm-linux-gnueabi and for arm64 you need: $ sudo apt-get install binutils-aarch64-linux-gnu Generating the rootfs --------------------- The `eng/common/cross/build-rootfs.sh` script can be used to download the files needed for cross compilation. It will generate an Ubuntu 16.04 rootfs as this is what CoreFX targets. Usage: ./eng/common/cross/build-rootfs.sh [BuildArch] [LinuxCodeName] [lldbx.y] [--skipunmount] --rootfsdir <directory>] BuildArch can be: arm, armel, arm64, x86 LinuxCodeName - optional, Code name for Linux, can be: trusty, xenial(default), zesty, bionic, alpine. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen. lldbx.y - optional, LLDB version, can be: lldb3.9(default), lldb4.0, lldb5.0, lldb6.0 no-lldb. Ignored for alpine The `build-rootfs.sh` script must be run as root, as it has to make some symlinks to the system. It will, by default, generate the rootfs in `cross/rootfs/<BuildArch>` however this can be changed by setting the `ROOTFS_DIR` environment variable or by using --rootfsdir. For example, to generate an arm rootfs: $ sudo ./eng/common/cross/build-rootfs.sh arm and if you wanted to generate the rootfs elsewhere: $ sudo ./build-rootfs.sh arm --rootfsdir /mnt/corefx-cross/arm Cross compiling for native CoreFX --------------------------------- Once the rootfs has been generated, it will be possible to cross compile CoreFX. If `ROOTFS_DIR` was set when generating the rootfs, then it must also be set when running `build.sh`. So, without `ROOTFS_DIR`: $ ./src/Native/build-native.sh debug arm verbose cross And with: $ ROOTFS_DIR=/mnt/corefx-cross/arm ./src/Native/build-native.sh debug arm verbose cross As usual the generated binaries will be found in `artifacts/bin/TargetOS.BuildArch.BuildType/native` as following: $ ls -al ./artifacts/bin/Linux.arm.Debug/native total 988 drwxrwxr-x 2 lgs lgs 4096 3 6 18:33 . drwxrwxr-x 3 lgs lgs 4096 3 6 18:33 .. -rw-r--r-- 1 lgs lgs 19797 3 6 18:33 System.IO.Compression.Native.so -rw-r--r-- 1 lgs lgs 428232 3 6 18:33 System.Native.a -rw-r--r-- 1 lgs lgs 228279 3 6 18:33 System.Native.so -rw-r--r-- 1 lgs lgs 53089 3 6 18:33 System.Net.Http.Native.so -rw-r--r-- 1 lgs lgs 266720 3 6 18:33 System.Security.Cryptography.Native.so $ file ./artifacts/bin/Linux.arm.Debug/native/System.Native.so ./bin/Linux.arm.Debug/native/System.Native.so: ELF 32-bit LSB shared object, ARM, EABI5 version 1 (SYSV), dynamically linked, BuildID[sha1]=fac50f1bd657c1759f0ad6cf5951511ddf252e67, not stripped Compiling for managed CoreFX ============================ The managed components of CoreFX are architecture-independent and thus do not require a special build for arm, armel or arm64. Many of the managed binaries are also OS-independent, e.g. System.Linq.dll, while some are OS-specific, e.g. System.IO.FileSystem.dll, with different builds for Windows and Linux. $ ROOTFS_DIR=/mnt/corefx-cross/arm ./build.sh --arch arm You can also build just managed code with: $ ./build.sh --arch arm /p:BuildNative=false The output is at `artifacts/bin/[BuildSettings]` where `BuildSettings` looks something like `net5.0-<TargetOS>-Debug-<Architecture>`. Ex: `artifacts/bin/net5.0-Linux-Debug-x64`. For more details on the build configurations see [project-guidelines](/docs/coding-guidelines/project-guidelines.md) Building corefx for Linux ARM Emulator ======================================= It is possible to build corefx binaries (native and managed) for the Linux ARM Emulator (latest version provided here: [#5394](https://github.com/dotnet/runtime/issues/5394)). The `scripts/arm32_ci_script.sh` script does this. The following instructions assume that: * You have set up the extracted emulator at `/opt/linux-arm-emulator` (such that `/opt/linux-arm-emulator/platform/rootfs-t30.ext4` exists) * The mount path for the emulator rootfs is `/opt/linux-arm-emulator-root` (change this path if you have a working directory at this path). All the following instructions are for the Release mode. Change the commands and files accordingly for the Debug mode. To just build the native and managed corefx binaries for the Linux ARM Emulator, run the following command: ``` prajwal@ubuntu ~/corefx $ ./scripts/arm32_ci_script.sh \ --emulatorPath=/opt/linux-arm-emulator \ --mountPath=/opt/linux-arm-emulator-root \ --buildConfig=Release ``` The Linux ARM Emulator is based on the soft floating point and thus the native binaries are generated for the armel architecture. The corefx binaries generated by the above command can be found at `~/corefx/artifacts/bin/Linux.armel.Release`, `~/corefx/artifacts/bin/Linux.AnyCPU.Release`, `~/corefx/artifacts/bin/Unix.AnyCPU.Release`, and `~/corefx/artifacts/bin/AnyOS.AnyCPU.Release`. Build corefx for a new architecture =================================== When building for a new architecture you will need to build the native pieces separate from the managed pieces in order to correctly boot strap the native runtime. Instead of calling build.sh directly you should instead split the calls like such: Example building for armel ``` src/Native/build-native.sh armel --> Output goes to artifacts/bin/runtime/net5.0-Linux-Debug-armel build /p:TargetArchitecture=x64 /p:BuildNative=false --> Output goes to artifacts/bin/runtime/net5.0-Linux-Debug-x64 ``` The reason you need to build the managed portion for x64 is because it depends on runtime packages for the new architecture which don't exist yet so we use another existing architecture such as x64 as a proxy for building the managed binaries. Similar if you want to try and run tests you will have to copy the managed assemblies from the proxy directory (i.e. `net5.0-Linux-Debug-x64`) to the new architecture directory (i.e `net5.0-Linux-Debug-armel`) and run code via another host such as corerun because dotnet is at a higher level and most likely doesn't exist for the new architecture yet. Once all the necessary builds are setup and packages are published the splitting of the build and manual creation of the runtime should no longer be necessary.
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/coreclr/scripts/superpmi-replay.proj
<Project Sdk="Microsoft.DotNet.Helix.Sdk" DefaultTargets="Test"> <!-- This is useful for local testing to print the produced helix items To use this when you are changing how items are produced, uncomment the target and replace the Project item at the top of the file with this: <Project DefaultTargets="printItems"> Once you've done that you can run this to see the results: dotnet msbuild .\superpmi-replay.proj /v:n --> <!-- <PropertyGroup> <HelixTargetQueues>Some_Queue</HelixTargetQueues> <Platform>Windows</Platform> <Architecture>x64</Architecture> </PropertyGroup> <Target Name="printItems"> <Message Text="@(HelixWorkItem -> 'name: %(HelixWorkItem.Identity) dir: %(HelixWorkItem.PayloadDirectory) pre: %(HelixWorkItem.PreCommands) command: %(HelixWorkItem.Command) post: %(HelixWorkItem.PostCommands) timeout: %(HelixWorkItem.Timeout) '"/> </Target> --> <PropertyGroup> <Python>%HELIX_PYTHONPATH%</Python> <ProductDirectory>%HELIX_CORRELATION_PAYLOAD%</ProductDirectory> <SuperpmiLogsLocation>%HELIX_WORKITEM_UPLOAD_ROOT%</SuperpmiLogsLocation> <!-- Workaround until https://github.com/dotnet/arcade/pull/6179 is not available --> <HelixResultsDestinationDir>$(BUILD_SOURCESDIRECTORY)\artifacts\helixresults</HelixResultsDestinationDir> <WorkItemCommand>$(Python) $(ProductDirectory)\superpmi_replay.py -jit_directory $(ProductDirectory)</WorkItemCommand> <WorkItemTimeout>3:15</WorkItemTimeout> </PropertyGroup> <PropertyGroup> <EnableAzurePipelinesReporter>false</EnableAzurePipelinesReporter> <EnableXUnitReporter>false</EnableXUnitReporter> <Creator>$(_Creator)</Creator> <HelixAccessToken>$(_HelixAccessToken)</HelixAccessToken> <HelixBuild>$(_HelixBuild)</HelixBuild> <HelixSource>$(_HelixSource)</HelixSource> <HelixTargetQueues>$(_HelixTargetQueues)</HelixTargetQueues> <HelixType>$(_HelixType)</HelixType> </PropertyGroup> <ItemGroup> <HelixCorrelationPayload Include="$(CorrelationPayloadDirectory)"> <PayloadDirectory>%(Identity)</PayloadDirectory> </HelixCorrelationPayload> </ItemGroup> <ItemGroup Condition="'$(Architecture)' == 'x64'"> <!-- Use 2 partitions for each run on an x64 machine --> <SPMI_Partition Include="win-x64-1" Platform="windows" Architecture="x64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="win-x64-2" Platform="windows" Architecture="x64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="win-arm64-1" Platform="windows" Architecture="arm64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="win-arm64-2" Platform="windows" Architecture="arm64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="unix-x64-1" Platform="Linux" Architecture="x64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="unix-x64-2" Platform="Linux" Architecture="x64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="linux-arm64-1" Platform="Linux" Architecture="arm64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="linux-arm64-2" Platform="Linux" Architecture="arm64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="osx-arm64-1" Platform="OSX" Architecture="arm64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="osx-arm64-2" Platform="OSX" Architecture="arm64" Partition="2" PartitionCount="2"/> </ItemGroup> <ItemGroup Condition="'$(Architecture)' == 'x86'"> <!-- The x86 machine replays are slower than x64, so use 3 partitions for each run on x86 --> <SPMI_Partition Include="win-x86-1" Platform="windows" Architecture="x86" Partition="1" PartitionCount="3"/> <SPMI_Partition Include="win-x86-2" Platform="windows" Architecture="x86" Partition="2" PartitionCount="3"/> <SPMI_Partition Include="win-x86-3" Platform="windows" Architecture="x86" Partition="3" PartitionCount="3"/> <SPMI_Partition Include="unix-arm-1" Platform="Linux" Architecture="arm" Partition="1" PartitionCount="3"/> <SPMI_Partition Include="unix-arm-2" Platform="Linux" Architecture="arm" Partition="2" PartitionCount="3"/> <SPMI_Partition Include="unix-arm-3" Platform="Linux" Architecture="arm" Partition="3" PartitionCount="3"/> </ItemGroup> <ItemGroup> <HelixWorkItem Include="@(SPMI_Partition)"> <Command>$(WorkItemCommand) -arch %(HelixWorkItem.Architecture) -platform %(HelixWorkItem.Platform) -partition %(HelixWorkItem.Partition) -partition_count %(HelixWorkItem.PartitionCount) -log_directory $(SuperpmiLogsLocation)</Command> <Timeout>$(WorkItemTimeout)</Timeout> <DownloadFilesFromResults>superpmi_%(HelixWorkItem.Platform)_%(HelixWorkItem.Architecture)_%(HelixWorkItem.Partition).log</DownloadFilesFromResults> </HelixWorkItem> </ItemGroup> </Project>
<Project Sdk="Microsoft.DotNet.Helix.Sdk" DefaultTargets="Test"> <!-- This is useful for local testing to print the produced helix items To use this when you are changing how items are produced, uncomment the target and replace the Project item at the top of the file with this: <Project DefaultTargets="printItems"> Once you've done that you can run this to see the results: dotnet msbuild .\superpmi-replay.proj /v:n --> <!-- <PropertyGroup> <HelixTargetQueues>Some_Queue</HelixTargetQueues> <Platform>Windows</Platform> <Architecture>x64</Architecture> </PropertyGroup> <Target Name="printItems"> <Message Text="@(HelixWorkItem -> 'name: %(HelixWorkItem.Identity) dir: %(HelixWorkItem.PayloadDirectory) pre: %(HelixWorkItem.PreCommands) command: %(HelixWorkItem.Command) post: %(HelixWorkItem.PostCommands) timeout: %(HelixWorkItem.Timeout) '"/> </Target> --> <PropertyGroup> <Python>%HELIX_PYTHONPATH%</Python> <ProductDirectory>%HELIX_CORRELATION_PAYLOAD%</ProductDirectory> <SuperpmiLogsLocation>%HELIX_WORKITEM_UPLOAD_ROOT%</SuperpmiLogsLocation> <!-- Workaround until https://github.com/dotnet/arcade/pull/6179 is not available --> <HelixResultsDestinationDir>$(BUILD_SOURCESDIRECTORY)\artifacts\helixresults</HelixResultsDestinationDir> <WorkItemCommand>$(Python) $(ProductDirectory)\superpmi_replay.py -jit_directory $(ProductDirectory)</WorkItemCommand> <WorkItemTimeout>3:15</WorkItemTimeout> </PropertyGroup> <PropertyGroup> <EnableAzurePipelinesReporter>false</EnableAzurePipelinesReporter> <EnableXUnitReporter>false</EnableXUnitReporter> <Creator>$(_Creator)</Creator> <HelixAccessToken>$(_HelixAccessToken)</HelixAccessToken> <HelixBuild>$(_HelixBuild)</HelixBuild> <HelixSource>$(_HelixSource)</HelixSource> <HelixTargetQueues>$(_HelixTargetQueues)</HelixTargetQueues> <HelixType>$(_HelixType)</HelixType> </PropertyGroup> <ItemGroup> <HelixCorrelationPayload Include="$(CorrelationPayloadDirectory)"> <PayloadDirectory>%(Identity)</PayloadDirectory> </HelixCorrelationPayload> </ItemGroup> <ItemGroup Condition="'$(Architecture)' == 'x64'"> <!-- Use 2 partitions for each run on an x64 machine --> <SPMI_Partition Include="win-x64-1" Platform="windows" Architecture="x64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="win-x64-2" Platform="windows" Architecture="x64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="win-arm64-1" Platform="windows" Architecture="arm64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="win-arm64-2" Platform="windows" Architecture="arm64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="unix-x64-1" Platform="Linux" Architecture="x64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="unix-x64-2" Platform="Linux" Architecture="x64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="linux-arm64-1" Platform="Linux" Architecture="arm64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="linux-arm64-2" Platform="Linux" Architecture="arm64" Partition="2" PartitionCount="2"/> <SPMI_Partition Include="osx-arm64-1" Platform="OSX" Architecture="arm64" Partition="1" PartitionCount="2"/> <SPMI_Partition Include="osx-arm64-2" Platform="OSX" Architecture="arm64" Partition="2" PartitionCount="2"/> </ItemGroup> <ItemGroup Condition="'$(Architecture)' == 'x86'"> <!-- The x86 machine replays are slower than x64, so use 3 partitions for each run on x86 --> <SPMI_Partition Include="win-x86-1" Platform="windows" Architecture="x86" Partition="1" PartitionCount="3"/> <SPMI_Partition Include="win-x86-2" Platform="windows" Architecture="x86" Partition="2" PartitionCount="3"/> <SPMI_Partition Include="win-x86-3" Platform="windows" Architecture="x86" Partition="3" PartitionCount="3"/> <SPMI_Partition Include="unix-arm-1" Platform="Linux" Architecture="arm" Partition="1" PartitionCount="3"/> <SPMI_Partition Include="unix-arm-2" Platform="Linux" Architecture="arm" Partition="2" PartitionCount="3"/> <SPMI_Partition Include="unix-arm-3" Platform="Linux" Architecture="arm" Partition="3" PartitionCount="3"/> </ItemGroup> <ItemGroup> <HelixWorkItem Include="@(SPMI_Partition)"> <Command>$(WorkItemCommand) -arch %(HelixWorkItem.Architecture) -platform %(HelixWorkItem.Platform) -partition %(HelixWorkItem.Partition) -partition_count %(HelixWorkItem.PartitionCount) -log_directory $(SuperpmiLogsLocation)</Command> <Timeout>$(WorkItemTimeout)</Timeout> <DownloadFilesFromResults>superpmi_%(HelixWorkItem.Platform)_%(HelixWorkItem.Architecture)_%(HelixWorkItem.Partition).log</DownloadFilesFromResults> </HelixWorkItem> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Net.Http/tests/EnterpriseTests/README.md
# Enterprise Scenario Testing Detailed instructions for running these tests is located here: src\libraries\Common\tests\System\Net\EnterpriseTests\setup\README.md
# Enterprise Scenario Testing Detailed instructions for running these tests is located here: src\libraries\Common\tests\System\Net\EnterpriseTests\setup\README.md
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Microsoft.Interop.LibraryImportGenerator.props
<Project> <!-- Define all of the configuration options supported for the LibraryImportGenerator. To use, set an MSBuild property with the name of the option to `true`. See OptionsHelper.cs for more information on usage. --> <ItemGroup> <!-- Use the System.Runtime.InteropServices.Marshal type instead of the System.Runtime.InteropServices.MarshalEx type when emitting code. --> <CompilerVisibleProperty Include="LibraryImportGenerator_UseMarshalType" /> <!-- Generate a stub that forwards to a runtime implemented P/Invoke stub instead of generating a stub that handles all of the marshalling. --> <CompilerVisibleProperty Include="LibraryImportGenerator_GenerateForwarders" /> </ItemGroup> </Project>
<Project> <!-- Define all of the configuration options supported for the LibraryImportGenerator. To use, set an MSBuild property with the name of the option to `true`. See OptionsHelper.cs for more information on usage. --> <ItemGroup> <!-- Use the System.Runtime.InteropServices.Marshal type instead of the System.Runtime.InteropServices.MarshalEx type when emitting code. --> <CompilerVisibleProperty Include="LibraryImportGenerator_UseMarshalType" /> <!-- Generate a stub that forwards to a runtime implemented P/Invoke stub instead of generating a stub that handles all of the marshalling. --> <CompilerVisibleProperty Include="LibraryImportGenerator_GenerateForwarders" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./docs/coding-guidelines/breaking-change-definitions.md
Breaking Change Definitions =========================== Behavioral Change ----------------- A behavioral change represents changes to the behavior of a member. A behavioral change may including throwing a new exception, adding or removing internal method calls, or alternating the way in which a return value is calculated. Behavioral changes can be the hardest type of change to categorize as acceptable or not - they can be severe in impact, or relatively innocuous. Binary Compatibility -------------------- Refers to the ability of existing consumers of an API to be able to use a newer version without recompilation. By definition, if an assembly's public signatures have been removed, or altered so that consumers can no longer access the same interface exposed by the assembly, the change is said to be a _binary incompatible change_. Source Compatibility -------------------- Refers to the ability of existing consumers of an API to recompile against a newer version without any source changes. By definition, if a consumer needs to make changes to its code in order for it to build successfully against a newer version of an API, the change is said to be a _source incompatible change_. Design-Time Compatibility ------------------------- _Design-time compatibility_ refers to preserving the design-time experience across versions of Visual Studio and other design-time environments. This can involve details around the UI of the designer, but by far the most interesting design-time compatibility is project compatibility. A potential project (or solution), must be able to be opened, and used on a newer version of a designer. Backwards Compatibility ----------------------- _Backwards compatibility_ refers to the ability of an existing consumer of an API to run against, and behave in the same way against a newer version. By definition, if a consumer is not able to run, or behaves differently against the newer version of the API, then the API is said to be _backwards incompatible_. Changes that affect backwards compatibility are strongly discouraged. All alternates should be actively considered, since developers will, by default, expect backwards compatibility in newer versions of an API. Forwards Compatibility ---------------------- _Forwards compatibility_ is the exact reverse of backwards compatibility; it refers to the ability of an existing consumer of an API to run against, and behave in the way against a _older_ version. By definition, if a consumer is not able to run, or behaves differently against an older version of the API, then the API is said to be _forwards incompatible_. Changes that affect forwards compatibility are generally less pervasive, and there is not as stringent a demand to ensure that such changes are not introduced. Customers accept that a consumer which relies upon a newer API, may not function correctly against the older API. This document does not attempt to detail forwards incompatibilities.
Breaking Change Definitions =========================== Behavioral Change ----------------- A behavioral change represents changes to the behavior of a member. A behavioral change may including throwing a new exception, adding or removing internal method calls, or alternating the way in which a return value is calculated. Behavioral changes can be the hardest type of change to categorize as acceptable or not - they can be severe in impact, or relatively innocuous. Binary Compatibility -------------------- Refers to the ability of existing consumers of an API to be able to use a newer version without recompilation. By definition, if an assembly's public signatures have been removed, or altered so that consumers can no longer access the same interface exposed by the assembly, the change is said to be a _binary incompatible change_. Source Compatibility -------------------- Refers to the ability of existing consumers of an API to recompile against a newer version without any source changes. By definition, if a consumer needs to make changes to its code in order for it to build successfully against a newer version of an API, the change is said to be a _source incompatible change_. Design-Time Compatibility ------------------------- _Design-time compatibility_ refers to preserving the design-time experience across versions of Visual Studio and other design-time environments. This can involve details around the UI of the designer, but by far the most interesting design-time compatibility is project compatibility. A potential project (or solution), must be able to be opened, and used on a newer version of a designer. Backwards Compatibility ----------------------- _Backwards compatibility_ refers to the ability of an existing consumer of an API to run against, and behave in the same way against a newer version. By definition, if a consumer is not able to run, or behaves differently against the newer version of the API, then the API is said to be _backwards incompatible_. Changes that affect backwards compatibility are strongly discouraged. All alternates should be actively considered, since developers will, by default, expect backwards compatibility in newer versions of an API. Forwards Compatibility ---------------------- _Forwards compatibility_ is the exact reverse of backwards compatibility; it refers to the ability of an existing consumer of an API to run against, and behave in the way against a _older_ version. By definition, if a consumer is not able to run, or behaves differently against an older version of the API, then the API is said to be _forwards incompatible_. Changes that affect forwards compatibility are generally less pervasive, and there is not as stringent a demand to ensure that such changes are not introduced. Customers accept that a consumer which relies upon a newer API, may not function correctly against the older API. This document does not attempt to detail forwards incompatibilities.
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./docs/project/issue-guide.md
Issue Guide =========== This page outlines how the CoreFx team thinks about and handles issues. For us, issues on GitHub represent actionable work that should be done at some future point. It may be as simple as a small product or test bug or as large as the work tracking the design of a new feature. However, it should be work that falls under the charter of CoreFx, which is a collection of foundational libraries that make up the .NET Core development stack. We will keep issues open even if the CoreFx team internally has no plans to address them in an upcoming release, as long as we consider the issue to fall under our purview. ### When we close issues As noted above, we don't close issues just because we don't plan to address them in an upcoming release. So why do we close issues? There are few major reasons: 1. Issues unrelated to CoreFx. When possible, we'll try to find a better home for the issue and point you to it. 2. Cross cutting work better suited for another team. Sometimes the line between the framework, languages and runtime blurs. For some issues, we may feel that the work is better suited for the runtime team, language team or other partner. In these cases, we'll close the issue and open it with the partner team. If they end up not deciding to take on the issue, we can reconsider it here. 3. Nebulous and Large open issues. Large open issues are sometimes better suited for [User Voice](http://visualstudio.uservoice.com/forums/121579-visual-studio/category/31481--net), especially when the work will cross the boundaries of the framework, language and runtime. A good example of this is the SIMD support we recently added to CoreFx. This started as a [User Voice request](https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/2212443-c-and-simd), and eventually turned into work for both the core libraries and runtime. Sometimes after debate, we'll decide an issue isn't a good fit for CoreFx. In that case, we'll also close it. Because of this, we ask that you don't start working on an issue until it's tagged with [up-for-grabs](https://github.com/dotnet/runtime/labels/up-for-grabs) or [api-approved](https://github.com/dotnet/runtime/labels/api-approved). Both you and the team will be unhappy if you spend time and effort working on a change we'll ultimately be unable to take. We try to avoid that. ### Labels We use GitHub [labels](https://github.com/dotnet/runtime/labels) on our issues in order to classify them. We have the following categories per issue: * **Area**: These area-&#42; labels (e.g. [area-System.Collections](https://github.com/dotnet/runtime/labels/area-System.Collections)) call out the assembly or assemblies the issue applies to. In addition to labels per assembly, we have a few other area labels: [area-Infrastructure](https://github.com/dotnet/runtime/labels/area-Infrastructure), for issues that relate to our build or test infrastructure, and [area-Meta](https://github.com/dotnet/runtime/labels/area-Meta) for issues that deal with the repository itself, the direction of the .NET Core Platform, our processes, etc. See [full list of areas](#areas). * **Issue Type**: These labels classify the type of issue. We use the following types: * [bug](https://github.com/dotnet/runtime/labels/bug): Bugs in an assembly. * api-&#42; ([api-approved](https://github.com/dotnet/runtime/labels/api-approved), [api-needs-work](https://github.com/dotnet/runtime/labels/api-needs-work), [api-ready-for-review](https://github.com/dotnet/runtime/labels/api-ready-for-review)): Issues which would add APIs to an assembly (see [API Review process](api-review-process.md) for details). * [enhancement](https://github.com/dotnet/runtime/labels/enhancement): Improvements to an assembly which do not add new APIs (e.g. performance improvements, code cleanup). * [test bug](https://github.com/dotnet/runtime/labels/test%20bug): Bugs in the tests for a specific assembly. * [test enhancement](https://github.com/dotnet/runtime/labels/test%20enhancement): Improvements in the tests for a specific assembly (e.g. improving test coverage). * [documentation](https://github.com/dotnet/runtime/labels/documentation): Issues related to documentation (e.g. incorrect documentation, enhancement requests). * [question](https://github.com/dotnet/runtime/labels/question): Questions about the product, source code, etc. * **Other**: * [easy](https://github.com/dotnet/runtime/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20label%3Aeasy%20no%3Aassignee) - Good for starting contributors. * [up-for-grabs](https://github.com/dotnet/runtime/labels/up-for-grabs): Small sections of work which we believe are well scoped. These sorts of issues are a good place to start if you are new. Anyone is free to work on these issues. * [needs more info](https://github.com/dotnet/runtime/labels/needs%20more%20info): Issues which need more information to be actionable. Usually this will be because we can't reproduce a reported bug. We'll close these issues after a little bit if we haven't gotten actionable information, but we welcome folks who have acquired more information to reopen the issue. * [wishlist](https://github.com/dotnet/runtime/issues?q=is%3Aissue+is%3Aopen+label%3Awishlist) - Issues on top of our backlog we won't likely get to. Warning: Might not be easy. In addition to the above, we have a handful of other labels we use to help classify our issues. Some of these tag cross cutting concerns (e.g. [tenet-performance](https://github.com/dotnet/runtime/labels/tenet-performance)), whereas others are used to help us track additional work needed before closing an issue (e.g. [api-needs-exposed](https://github.com/dotnet/runtime/labels/api-needs-exposed)). ### Milestones We use [milestones](https://github.com/dotnet/runtime/milestones) to prioritize work for each upcoming release to NuGet.org. ### Assignee We assign each issue to assignee, when the assignee is ready to pick up the work and start working on it. If the issue is not assigned to anyone and you want to pick it up, please say so - we will assign the issue to you. If the issue is already assigned to someone, please coordinate with the assignee before you start working on it. ### Areas Areas are tracked by labels area-&#42; (e.g. area-System.Collections). Each area typically corresponds to one or more contract assemblies. To view owners for each area in this repository check out the [area-owners.md](https://github.com/dotnet/runtime/blob/main/docs/area-owners.md) page. ### Community Partner Experts | Area | Owners / experts | Description | |-------------|------------------|-------------| | Tizen | [@alpencolt](https://github.com/alpencolt), [@gbalykov](https://github.com/gbalykov) | For issues around Tizen CI and build issues | ### Triage rules - simplified 1. Each issue has exactly one **area-&#42;** label 1. Issue has no **Assignee**, unless someone is working on the issue at the moment 1. Use **up-for-grabs** as much as possible, ideally with a quick note about next steps / complexity of the issue 1. Set milestone to **Future**, unless you can 95%-commit you can fund the issue in specific milestone 1. Each issue has exactly one "*issue type*" label (**bug**, **enhancement**, **api-needs-work**, **test bug**, **test enhancement**, **question**, **documentation**, etc.) 1. Don't be afraid to say no, or close issues - just explain why and be polite 1. Don't be afraid to be wrong - just be flexible when new information appears Feel free to use other labels if it helps your triage efforts (e.g. **needs more info**, **Design Discussion**, **blocked**, **blocking-partner**, **tenet-performance**, **tenet-compatibility**, **os-linux**/**os-windows**/**os-mac-os-x**/**os-unsupported**, **os-windows-uwp**/**os-windows-wsl**, **arch-arm32**/**arch-arm64**) #### Motivation for triage rules 1. Each issue has exactly one **area-\*** label * Motivation: Issues with multiple areas have loose responsibility (everyone blames the other side) and issues are double counted in reports. 1. Issue has no **Assignee**, unless someone is working on the issue at the moment * Motivation: Observation is that contributors are less likely to grab assigned issues, no matter what the repo rules say. 1. Use **up-for-grabs** as much as possible, ideally with a quick note about next steps / complexity of the issue * Note: Per http://up-for-grabs.net, such issues should be no longer than few nights' worth of work. They should be actionable (i.e. no misterious CI failures or UWP issues that can't be tested in the open). 1. Set milestone to **Future**, unless you can 95%-commit you can fund the issue in specific milestone * Motivation: Helps communicate desire/timeline to community. Can spark further priority/impact discussion. 1. Each issue has exactly one "*issue type*" label (**bug**, **enhancement**, **api-needs-work**, **test bug**, **test enhancement**, **question**, **documentation**, etc.) * Don't be afraid to be wrong when deciding 'bug' vs. 'test bug' (flip a coin if you must). The most useful values for tracking are 'api-&#42;' vs. 'enhancement', 'question', and 'documentation'. * Note: The **api-\*** labels are important for tracking API approvals, the other *issue type* labels are in practice optional. 1. Don't be afraid to say no, or close issues - just explain why and be polite 1. Don't be afraid to be wrong - just be flexible when new information appears #### PR rules 1. Each PR has exactly one **area-\*** label * Movitation: Area owners will get email notification about new issue in their area. 1. PR has **Assignee** set to author of the PR, if it is non-CoreFX engineer, then area owners are co-assignees * Motivation #1: Area owners are responsible to do code reviews for PRs from external contributors. CoreFX engineers know how to get code reviews from others. * Motivation #2: Assignees will get notifications for anything happening on the PR. 1. [Optional] Set milestone according to the branch the PR is against (main = 6.0, release/5.0 = 5.0) * Motivation: Easier to track and audit where which fix ended up and if it needs to be ported into another branch (hence reflecting branch the specific PR ended up and not the abstract issue). * Note: This is easily done after merge via simple queries & bulk-edits, you don't have to do this one. 1. Any other labels on PRs are superfluous and not needed (exceptions: **blocked**, **NO MERGE**) * Motivation: All the important info (*issue type* label, api approval label, OS label, etc.) is already captured on the associated issue. 1. Push PRs forward, don't let them go stale (response every 5+ days, ideally no PRs older than 2 weeks) 1. Stuck or long-term blocked PRs (e.g. due to missing API approval, etc.) should be closed and reopened once they are unstuck * Motivation: Keep only active PRs. WIP (work-in-progress) PRs should be rare and should not become stale (2+ weeks old). If a PR is stale and there is not immediate path forward, consider closing the PR until it is unblocked/unstuck. 1. PR should be linked to related issue, use [auto-closing](https://help.github.com/articles/closing-issues-via-commit-messages/) (add "Fixes #12345" into your PR description)
Issue Guide =========== This page outlines how the CoreFx team thinks about and handles issues. For us, issues on GitHub represent actionable work that should be done at some future point. It may be as simple as a small product or test bug or as large as the work tracking the design of a new feature. However, it should be work that falls under the charter of CoreFx, which is a collection of foundational libraries that make up the .NET Core development stack. We will keep issues open even if the CoreFx team internally has no plans to address them in an upcoming release, as long as we consider the issue to fall under our purview. ### When we close issues As noted above, we don't close issues just because we don't plan to address them in an upcoming release. So why do we close issues? There are few major reasons: 1. Issues unrelated to CoreFx. When possible, we'll try to find a better home for the issue and point you to it. 2. Cross cutting work better suited for another team. Sometimes the line between the framework, languages and runtime blurs. For some issues, we may feel that the work is better suited for the runtime team, language team or other partner. In these cases, we'll close the issue and open it with the partner team. If they end up not deciding to take on the issue, we can reconsider it here. 3. Nebulous and Large open issues. Large open issues are sometimes better suited for [User Voice](http://visualstudio.uservoice.com/forums/121579-visual-studio/category/31481--net), especially when the work will cross the boundaries of the framework, language and runtime. A good example of this is the SIMD support we recently added to CoreFx. This started as a [User Voice request](https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/2212443-c-and-simd), and eventually turned into work for both the core libraries and runtime. Sometimes after debate, we'll decide an issue isn't a good fit for CoreFx. In that case, we'll also close it. Because of this, we ask that you don't start working on an issue until it's tagged with [up-for-grabs](https://github.com/dotnet/runtime/labels/up-for-grabs) or [api-approved](https://github.com/dotnet/runtime/labels/api-approved). Both you and the team will be unhappy if you spend time and effort working on a change we'll ultimately be unable to take. We try to avoid that. ### Labels We use GitHub [labels](https://github.com/dotnet/runtime/labels) on our issues in order to classify them. We have the following categories per issue: * **Area**: These area-&#42; labels (e.g. [area-System.Collections](https://github.com/dotnet/runtime/labels/area-System.Collections)) call out the assembly or assemblies the issue applies to. In addition to labels per assembly, we have a few other area labels: [area-Infrastructure](https://github.com/dotnet/runtime/labels/area-Infrastructure), for issues that relate to our build or test infrastructure, and [area-Meta](https://github.com/dotnet/runtime/labels/area-Meta) for issues that deal with the repository itself, the direction of the .NET Core Platform, our processes, etc. See [full list of areas](#areas). * **Issue Type**: These labels classify the type of issue. We use the following types: * [bug](https://github.com/dotnet/runtime/labels/bug): Bugs in an assembly. * api-&#42; ([api-approved](https://github.com/dotnet/runtime/labels/api-approved), [api-needs-work](https://github.com/dotnet/runtime/labels/api-needs-work), [api-ready-for-review](https://github.com/dotnet/runtime/labels/api-ready-for-review)): Issues which would add APIs to an assembly (see [API Review process](api-review-process.md) for details). * [enhancement](https://github.com/dotnet/runtime/labels/enhancement): Improvements to an assembly which do not add new APIs (e.g. performance improvements, code cleanup). * [test bug](https://github.com/dotnet/runtime/labels/test%20bug): Bugs in the tests for a specific assembly. * [test enhancement](https://github.com/dotnet/runtime/labels/test%20enhancement): Improvements in the tests for a specific assembly (e.g. improving test coverage). * [documentation](https://github.com/dotnet/runtime/labels/documentation): Issues related to documentation (e.g. incorrect documentation, enhancement requests). * [question](https://github.com/dotnet/runtime/labels/question): Questions about the product, source code, etc. * **Other**: * [easy](https://github.com/dotnet/runtime/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20label%3Aeasy%20no%3Aassignee) - Good for starting contributors. * [up-for-grabs](https://github.com/dotnet/runtime/labels/up-for-grabs): Small sections of work which we believe are well scoped. These sorts of issues are a good place to start if you are new. Anyone is free to work on these issues. * [needs more info](https://github.com/dotnet/runtime/labels/needs%20more%20info): Issues which need more information to be actionable. Usually this will be because we can't reproduce a reported bug. We'll close these issues after a little bit if we haven't gotten actionable information, but we welcome folks who have acquired more information to reopen the issue. * [wishlist](https://github.com/dotnet/runtime/issues?q=is%3Aissue+is%3Aopen+label%3Awishlist) - Issues on top of our backlog we won't likely get to. Warning: Might not be easy. In addition to the above, we have a handful of other labels we use to help classify our issues. Some of these tag cross cutting concerns (e.g. [tenet-performance](https://github.com/dotnet/runtime/labels/tenet-performance)), whereas others are used to help us track additional work needed before closing an issue (e.g. [api-needs-exposed](https://github.com/dotnet/runtime/labels/api-needs-exposed)). ### Milestones We use [milestones](https://github.com/dotnet/runtime/milestones) to prioritize work for each upcoming release to NuGet.org. ### Assignee We assign each issue to assignee, when the assignee is ready to pick up the work and start working on it. If the issue is not assigned to anyone and you want to pick it up, please say so - we will assign the issue to you. If the issue is already assigned to someone, please coordinate with the assignee before you start working on it. ### Areas Areas are tracked by labels area-&#42; (e.g. area-System.Collections). Each area typically corresponds to one or more contract assemblies. To view owners for each area in this repository check out the [area-owners.md](https://github.com/dotnet/runtime/blob/main/docs/area-owners.md) page. ### Community Partner Experts | Area | Owners / experts | Description | |-------------|------------------|-------------| | Tizen | [@alpencolt](https://github.com/alpencolt), [@gbalykov](https://github.com/gbalykov) | For issues around Tizen CI and build issues | ### Triage rules - simplified 1. Each issue has exactly one **area-&#42;** label 1. Issue has no **Assignee**, unless someone is working on the issue at the moment 1. Use **up-for-grabs** as much as possible, ideally with a quick note about next steps / complexity of the issue 1. Set milestone to **Future**, unless you can 95%-commit you can fund the issue in specific milestone 1. Each issue has exactly one "*issue type*" label (**bug**, **enhancement**, **api-needs-work**, **test bug**, **test enhancement**, **question**, **documentation**, etc.) 1. Don't be afraid to say no, or close issues - just explain why and be polite 1. Don't be afraid to be wrong - just be flexible when new information appears Feel free to use other labels if it helps your triage efforts (e.g. **needs more info**, **Design Discussion**, **blocked**, **blocking-partner**, **tenet-performance**, **tenet-compatibility**, **os-linux**/**os-windows**/**os-mac-os-x**/**os-unsupported**, **os-windows-uwp**/**os-windows-wsl**, **arch-arm32**/**arch-arm64**) #### Motivation for triage rules 1. Each issue has exactly one **area-\*** label * Motivation: Issues with multiple areas have loose responsibility (everyone blames the other side) and issues are double counted in reports. 1. Issue has no **Assignee**, unless someone is working on the issue at the moment * Motivation: Observation is that contributors are less likely to grab assigned issues, no matter what the repo rules say. 1. Use **up-for-grabs** as much as possible, ideally with a quick note about next steps / complexity of the issue * Note: Per http://up-for-grabs.net, such issues should be no longer than few nights' worth of work. They should be actionable (i.e. no misterious CI failures or UWP issues that can't be tested in the open). 1. Set milestone to **Future**, unless you can 95%-commit you can fund the issue in specific milestone * Motivation: Helps communicate desire/timeline to community. Can spark further priority/impact discussion. 1. Each issue has exactly one "*issue type*" label (**bug**, **enhancement**, **api-needs-work**, **test bug**, **test enhancement**, **question**, **documentation**, etc.) * Don't be afraid to be wrong when deciding 'bug' vs. 'test bug' (flip a coin if you must). The most useful values for tracking are 'api-&#42;' vs. 'enhancement', 'question', and 'documentation'. * Note: The **api-\*** labels are important for tracking API approvals, the other *issue type* labels are in practice optional. 1. Don't be afraid to say no, or close issues - just explain why and be polite 1. Don't be afraid to be wrong - just be flexible when new information appears #### PR rules 1. Each PR has exactly one **area-\*** label * Movitation: Area owners will get email notification about new issue in their area. 1. PR has **Assignee** set to author of the PR, if it is non-CoreFX engineer, then area owners are co-assignees * Motivation #1: Area owners are responsible to do code reviews for PRs from external contributors. CoreFX engineers know how to get code reviews from others. * Motivation #2: Assignees will get notifications for anything happening on the PR. 1. [Optional] Set milestone according to the branch the PR is against (main = 6.0, release/5.0 = 5.0) * Motivation: Easier to track and audit where which fix ended up and if it needs to be ported into another branch (hence reflecting branch the specific PR ended up and not the abstract issue). * Note: This is easily done after merge via simple queries & bulk-edits, you don't have to do this one. 1. Any other labels on PRs are superfluous and not needed (exceptions: **blocked**, **NO MERGE**) * Motivation: All the important info (*issue type* label, api approval label, OS label, etc.) is already captured on the associated issue. 1. Push PRs forward, don't let them go stale (response every 5+ days, ideally no PRs older than 2 weeks) 1. Stuck or long-term blocked PRs (e.g. due to missing API approval, etc.) should be closed and reopened once they are unstuck * Motivation: Keep only active PRs. WIP (work-in-progress) PRs should be rare and should not become stale (2+ weeks old). If a PR is stale and there is not immediate path forward, consider closing the PR until it is unblocked/unstuck. 1. PR should be linked to related issue, use [auto-closing](https://help.github.com/articles/closing-issues-via-commit-messages/) (add "Fixes #12345" into your PR description)
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/runtime/cjs/dotnet.cjs.extpost.js
var require = require || undefined; // if loaded into global namespace and configured with global Module, we will self start in compatibility mode const __isWorker = typeof globalThis.importScripts === "function"; let ENVIRONMENT_IS_GLOBAL = !__isWorker && (typeof globalThis.Module === "object" && globalThis.__dotnet_runtime === __dotnet_runtime); if (ENVIRONMENT_IS_GLOBAL) { createDotnetRuntime(() => { return globalThis.Module; }).then((exports) => exports); } else if (typeof globalThis.__onDotnetRuntimeLoaded === "function") { globalThis.__onDotnetRuntimeLoaded(createDotnetRuntime); }
var require = require || undefined; // if loaded into global namespace and configured with global Module, we will self start in compatibility mode const __isWorker = typeof globalThis.importScripts === "function"; let ENVIRONMENT_IS_GLOBAL = !__isWorker && (typeof globalThis.Module === "object" && globalThis.__dotnet_runtime === __dotnet_runtime); if (ENVIRONMENT_IS_GLOBAL) { createDotnetRuntime(() => { return globalThis.Module; }).then((exports) => exports); } else if (typeof globalThis.__onDotnetRuntimeLoaded === "function") { globalThis.__onDotnetRuntimeLoaded(createDotnetRuntime); }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./docs/design/features/native-hosting.md
# Native hosting Native hosting is the ability to host the .NET runtime in an arbitrary process, one which didn't start from .NET Core produced binaries. #### Terminology * "native host" - the code which uses the proposed APIs. Can be any non .NET Core application (.NET Core applications have easier ways to perform these scenarios). * "hosting components" - shorthand for .NET Core hosting components. Typically refers to `hostfxr` and `hostpolicy`. Sometimes also referred to simply as "host". * "host context" - state which `hostfxr` creates and maintains and represents a logical operation on the hosting components. ## Scenarios * **Hosting managed components** Native host which wants to load managed assembly and call into it for some functionality. Must support loading multiple such components side by side. * **Hosting managed apps** Native host which wants to run a managed app in-proc. Basically a different implementation of the existing .NET Core hosts (`dotnet.exe` or `apphost`). The intent is the ability to modify how the runtime starts and how the managed app is executed (and where it starts from). * **App using other .NET Core hosting services** App (native or .NET Core both) which needs to use some of the other services provided by the .NET Core hosting components. For example the ability to locate available SDKs and so on. ## Existing support * **C-style ABI in `coreclr`** `coreclr` exposes ABI to host the .NET runtime and run managed code already using C-style APIs. See this [header file](https://github.com/dotnet/runtime/blob/main/src/coreclr/hosts/inc/coreclrhost.h) for the exposed functions. This API requires the native host to locate the runtime and to fully specify all startup parameters for the runtime. There's no inherent interoperability between these APIs and the .NET SDK. * **COM-style ABI in `coreclr`** `coreclr` exposes COM-style ABI to host the .NET runtime and perform a wide range of operations on it. See this [header file](https://github.com/dotnet/runtime/blob/main/src/coreclr/pal/prebuilt/inc/mscoree.h) for more details. Similarly to the C-style ABI the COM-style ABI also requires the native host to locate the runtime and to fully specify all startup parameters. There's no inherent interoperability between these APIs and the .NET SDK. The COM-style ABI is deprecated and should not be used going forward. * **`hostfxr` and `hostpolicy` APIs** The hosting components of .NET Core already exposes some functionality as C-style ABI on either the `hostfxr` or `hostpolicy` libraries. These can execute application, determine available SDKs, determine native dependency locations, resolve component dependencies and so on. Unlike the above `coreclr` based APIs these don't require the caller to fully specify all startup parameters, instead these APIs understand artifacts produced by .NET SDK making it much easier to consume SDK produced apps/libraries. The native host is still required to locate the `hostfxr` or `hostpolicy` libraries. These APIs are also designed for specific narrow scenarios, any usage outside of these bounds is typically not possible. ## Scope This document focuses on hosting which cooperates with the .NET SDK and consumes the artifacts produced by building the managed app/libraries directly. It completely ignores the COM-style ABI as it's hard to use from some programming languages. As such the document explicitly excludes any hosting based on directly loading `coreclr`. Instead it focuses on using the existing .NET Core hosting components in new ways. For details on the .NET Core hosting components see [this document](https://github.com/dotnet/runtime/tree/main/docs/design/features/host-components.md). ## Longer term vision This section describes how we think the hosting components should evolve. It is expected that this won't happen in any single release, but each change should fit into this picture and hopefully move us closer to this goal. It is also expected that existing APIs won't change (no breaking changes) and thus it can happen that some of the APIs don't fit nicely into the picture. The hosting component APIs should provide functionality to cover a wide range of applications. At the same time it needs to stay in sync with what .NET Core SDK can produce so that the end-to-end experience is available. The overall goal of hosting components is to enable loading and executing managed code, this consists of four main steps: * **Locate and load hosting components** - How does a native host find and load the hosting components libraries. * **Locate the managed code and all its dependencies** - Determining where the managed code comes from (application, component, ...), what frameworks it relies on (framework resolution) and what dependencies it needs (`.deps.json` processing) * **Load the managed code into the process** - Specify the environment and settings for the runtime, locating or starting the runtime, deciding how to load the managed code into the runtime (which `AssemblyLoadContext` for example) and actually loading the managed code and its dependencies. * **Accessing and executing managed code** - Locate the managed entry point (for example assembly entry point `Main`, or a specific method to call, or some other means to transition control to the managed code) and exposing it into the native code (function pointer, COM interface, direct execution, ...). To achieve these we will structure the hosting components APIs into similar (but not exactly) 4 buckets. ### Locating hosting components This means providing APIs to find and load the hosting components. The end result should be that the native host has the right version of `hostfxr` loaded and can call its APIs. The exact solution is dependent on the native host application and its tooling. Ideally we would have a solution which works great for several common environments like C/C++ apps built in VS, C/C++ apps on Mac/Linux built with CMake (or similar) and so on. First step in this direction is the introduction of `nethost` library described below. ### Initializing host context The end result of this step should be an initialized host context for a given managed code input which the native host can use to load the managed code and execute it. The step should not actually load any runtime or managed code into the process. Finally this step must handle both processes which don't have any runtime loaded as well as processes which already have runtime loaded. Functionality performed by this step: * Locating and understanding the managed code input (app/component) * Resolving frameworks or handling self-contained * Resolving dependencies (`.deps.json` processing) * Populating runtime properties The vision is to expose a set of APIs in the form of `hostfxr_initialize_for_...` which would all perform the above functionality and would differ on how the managed code is located and used. So there should be a different API for loading applications and components at the very least. Going forward we can add API which can initialize the context from in-memory configurations, or API which can initialize an "empty" context (no custom code involved, just frameworks) and so on. First step in this direction is the introduction of these APIs as described below: * `hostfxr_initialize_for_dotnet_command_line` - this is the initialize for an application. The API is a bit more complicated as it allows for command line parsing as well. Eventually we might want to add another "initialize app" API without the command line support. * `hostfxr_initialize_for_runtime_config` - this is the initialize for a component (naming is not ideal, but can't be changed anymore). After this step it should be possible for the native host to inspect and potentially modify runtime properties. APIs like `hostfxr_get_runtime_property_value` and similar described below are an example of this. ### Loading managed code This step might be "virtual" in the sense that it's a way to setup the context for the desired functionality. In several scenarios it's not practical to be able to perform this step in separation from the "execute code" step below. The goal of this step is to determine which managed code to load, where it should be loaded into, and to setup the correct inputs so that runtime can perform the right dependency resolution. Logically this step finds/loads the runtime and initializes it before it can load any managed code into the process. The main flexibility this step should provide is to determine which assembly load context will be used for loading which code: * Load all managed code into the default load context * Load the specified custom managed code into an isolated load context Eventually we could also add functionality for example to setup the isolated load context for unloadability and so on. Note that there are no APIs proposed in this document which would only perform this step for now. All the APIs so far fold this step into the next one and perform both loading and executing of the managed code in one step. We should try to make this step more explicit in the future to allow for greater flexibility. After this step it is no longer possible to modify runtime properties (inspection is still allowed) since the runtime has been loaded. ### Accessing and executing managed code The end result of this step is either execution of the desired managed code, or returning a native callable representation of the managed code. The different options should include at least: * running an application (where the API takes over the thread and runs the application on behalf of the calling thread) - the `hostfxr_run_app` API described bellow is an example of this. * getting a native function pointer to a managed method - the `hostfxr_get_runtime_delegate` and the `hdt_load_assembly_and_get_function_pointer` described below is an example of this. * getting a native callable interface (COM) to a managed instance - the `hostfxr_get_runtime_delegate` and the `hdt_com_activation` described below is an example of this. * and more... ### Combinations Ideally it should be possible to combine the different types of initialization, loading and executing of managed code in any way the native host desires. In reality not all combinations are possible or practical. Few examples of combinations which we should probably NOT support (note that this may change in the future): * running a component as an application - runtime currently makes too many assumptions on what it means to "Run an application" * loading application into an isolated load context - for now there are too many limitations in the frameworks around secondary load contexts (several large framework features don't work well in a secondary ALC), so the hosting components should prevent this as a way to prevent users from getting into a bad situation. * loading multiple copies of the runtime into the process - support for side-by-side loading of different .NET Core runtime in a single process is not something we want to implement (at least yet). Hosting components should not allow this to make the user experience predictable. This means that full support for loading self-contained components at all times is not supported. Lot of other combinations will not be allowed simply as a result of shipping decisions. There's only so much functionality we can fit into any given release, so many combinations will be explicitly disabled to reduce the work necessary to actually ship this. The document below should describe which combinations are allowed in which release. ## High-level proposal In .NET Core 3.0 the hosting components (see [here](https://github.com/dotnet/runtime/tree/main/docs/design/features/host-components.md)) ships with several hosts. These are binaries which act as the entry points to the .NET Core hosting components/runtime: * The "muxer" (`dotnet.exe`) * The `apphost` (`.exe` which is part of the app) * The `comhost` (`.dll` which is part of the app and acts as COM server) * The `ijwhost` (`.dll` consumed via `.lib` used by IJW assemblies) Every one of these hosts serve different scenario and expose different APIs. The one thing they have in common is that their main purpose is to find the right `hostfxr`, load it and call into it to execute the desired scenario. For the most part all these hosts are basically just wrappers around functionality provided by `hostfxr`. The proposal is to add a new host library `nethost` which can be used by native host to easily locate `hostfxr`. Going forward the library could also include easy-to-use APIs for common scenarios - basically just a simplification of the `hostfxr` API surface. At the same time add the ability to pass additional runtime properties when starting the runtime through the hosting components APIs (starting app, loading component). This can be used by the native host to: * Register startup hook without modifying environment variables (which are inherited by child processes) * Introduce new runtime knobs which are only available for native hosts without the need to update the hosting components APIs every time. *Technical note: All strings in the proposed APIs are using the `char_t` in this document for simplicity. In real implementation they are of the type `pal::char_t`. In particular:* * *On Windows - they are `WCHAR *` using `UTF16` encoding* * *On Linux/macOS - they are `char *` using `UTF8` encoding* ## New host binary for finding `hostfxr` New library `nethost` which provides a way to locate the right `hostfxr`. This is a dynamically loaded library (`.dll`, `.so`, `.dylib`). For ease of use there is a header file for C/C++ apps as well as `.lib` for easy linking on Windows. Native hosts ship this library as part of the app. Unlike the `apphost`, `comhost` and `ijwhost`, the `nethost` will not be directly supported by the .NET SDK since it's target usage is not from .NET Core apps. The `nethost` is part of the `Microsoft.NETCore.DotNetAppHost` package. Users are expected to either download the package directly or rely on .NET SDK to pull it down. The binary itself should be signed by Microsoft as there will be no support for modifying the binary as part of custom application build (unlike `apphost`). ### Locate `hostfxr` ``` C++ struct get_hostfxr_parameters { size_t size; const char_t * assembly_path; const char_t * dotnet_root; }; int get_hostfxr_path( char_t * result_buffer, size_t * buffer_size, const get_hostfxr_parameters * parameters); ``` This API locates the `hostfxr` library and returns its path by populating `result_buffer`. * `result_buffer` - Buffer that will be populated with the hostfxr path, including a null terminator. * `buffer_size` - On input this points to the size of the `result_buffer` in `char_t` units. On output this points to the number of `char_t` units used from the `result_buffer` (including the null terminator). If `result_buffer` is `NULL` the input value is ignored and only the minimum required size in `char_t` units is set on output. * `parameters` - Optional. Additional parameters that modify the behaviour for locating the `hostfxr` library. If `NULL`, `hostfxr` is located using the environment variable or global registration * `size` - Size of the structure. This is used for versioning and should be set to `sizeof(get_hostfxr_parameters)`. * `assembly_path` - Optional. Path to the application or to the component's assembly. * If specified, `hostfxr` is located as if the `assembly_path` is an application with `apphost` * `dotnet_root` - Optional. Path to the root of a .NET Core installation (i.e. folder containing the dotnet executable). * If specified, `hostfxr` is located as if an application is started using `dotnet app.dll`, which means it will be searched for under the `dotnet_root` path and the `assembly_path` is ignored. `nethost` library uses the `__stdcall` calling convention. ## Improve API to run application and load components ### Goals * All hosts should be able to use the new API (whether they will is a separate question as the old API has to be kept for backward compat reasons) * Hide implementation details as much as possible * Make the API generally easier to use/understand * Give the implementation more freedom * Allow future improvements without breaking the API * Consider explicitly documenting types of behaviors which nobody should take dependency on (specifically failure scenarios) * Extensible * It should allow additional parameters to some of the operations without a need to add new exported APIs * It should allow additional interactions with the host - for example modifying how the runtime is initialized via some new options, without a need for a completely new set of APIs ### New scenarios The API should allow these scenarios: * Runtime properties * Specify additional runtime properties from the native host * Implement conflict resolution for runtime properties * Inspect calculated runtime properties (the ones calculated by `hostfxr`/`hostpolicy`) * Load managed component and get native function pointer for managed method * From native app start the runtime and load an assembly * The assembly is loaded in isolation and with all its dependencies as directed by `.deps.json` * The native app can get back a native function pointer which calls specified managed method * Get native function pointer for managed method * From native code get a native function pointer to already loaded managed method All the proposed APIs will be exports of the `hostfxr` library and will use the same calling convention and name mangling as existing `hostfxr` exports. ### Initialize host context All the "initialize" functions will * Process the `.runtimeconfig.json` * Resolve framework references and find actual frameworks * Find the root framework (`Microsoft.NETCore.App`) and load the `hostpolicy` from it * The `hostpolicy` will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. The functions will NOT load the CoreCLR runtime. They just prepare everything to the point where it can be loaded. The functions return a handle to a new host context: * The handle must be closed via `hostfxr_close`. * The handle is not thread safe - the consumer should only call functions on it from one thread at a time. The `hostfxr` will also track active runtime in the process. Due to limitations (and to simplify implementation) this tracking will actually not look at the actual `coreclr` module (or try to communicate with the runtime in any way). Instead `hostfxr` itself will track the host context initialization. The first host context initialization in the process will represent the "loaded runtime". It is only possible to have one "loaded runtime" in the process. Any subsequent host context initialization will just "attach" to the "loaded runtime" instead of creating a new one. ``` C typedef void* hostfxr_handle; struct hostfxr_initialize_parameters { size_t size; const char_t * host_path; const char_t * dotnet_root; }; ``` The `hostfxr_initialize_parameters` structure stores parameters which are common to all forms of initialization. * `size` - the size of the structure. This is used for versioning. Should be set to `sizeof(hostfxr_initialize_parameters)`. * `host_path` - path to the native host (typically the `.exe`). This value is not used for anything by the hosting components. It's just passed to the CoreCLR as the path to the executable. It can point to a file which is not executable itself, if such file doesn't exist (for example in COM activation scenarios this points to the `comhost.dll`). This is used by PAL to initialize internal command line structures, process name and so on. * `dotnet_root` - path to the root of the .NET Core installation in use. This typically points to the install location from which the `hostfxr` has been loaded. For example on Windows this would typically point to `C:\Program Files\dotnet`. The path is used to search for shared frameworks and potentially SDKs. ``` C int hostfxr_initialize_for_dotnet_command_line( int argc, const char_t * argv[], const hostfxr_initialize_parameters * parameters, hostfxr_handle * host_context_handle ); ``` Initializes the hosting components for running a managed application. The command line is parsed to determine the app path. The app path will be used to locate the `.runtimeconfig.json` and the `.deps.json` which will be used to load the application and its dependent frameworks. * `argc` and `argv` - the command line for running a managed application. These represent the arguments which would have been passed to the muxer if the app was being run from the command line. These are the parameters which are valid for the runtime installation by itself - SDK/CLI commands are not supported. For example, the arguments could be `app.dll app_argument_1 app_argument_2`. This API specifically doesn't support the `dotnet run` SDK command. * `parameters` - additional parameters - see `hostfxr_initialize_parameters` for details. (Could be made optional potentially) * `host_context_handle` - output parameter. On success receives an opaque value which identifies the initialized host context. The handle should be closed by calling `hostfxr_close`. This function only supports arguments for running an application as through the muxer. It does not support SDK commands. This function can only be called once per-process. It's not supported to run multiple apps in one process (even sequentially). This function will fail if there already is a CoreCLR running in the process as it's not possible to run two apps in a single process. This function supports both framework-dependent and self-contained applications. *Note: This is effectively a replacement for `hostfxr_main_startupinfo` and `hostfxr_main`. Currently it is not a goal to fully replace these APIs because they also support SDK commands which are special in lot of ways and don't fit well with the rest of the native hosting. There's no scenario right now which would require the ability to issue SDK commands from a native host. That said nothing in this proposal should block enabling even SDK commands through these APIs.* ``` C int hostfxr_initialize_for_runtime_config( const char_t * runtime_config_path, const hostfxr_initialize_parameters * parameters, hostfxr_handle * host_context_handle ); ``` This function would load the specified `.runtimeconfig.json`, resolve all frameworks, resolve all the assets from those frameworks and then prepare runtime initialization where the TPA contains only frameworks. Note that this case does NOT consume any `.deps.json` from the app/component (only processes the framework's `.deps.json`). This entry point is intended for `comhost`/`ijwhost`/`nethost` and similar scenarios. * `runtime_config_path` - path to the `.runtimeconfig.json` file to process. Unlike with `hostfxr_initialize_for_dotnet_command_line`, any `.deps.json` from the app/component will not be processed by the hosting components during the initialize call. * `parameters` - additional parameters - see `hostfxr_initialize_parameters` for details. (Could be made optional potentially) * `host_context_handle` - output parameter. On success receives an opaque value which identifies the initialized host context. The handle should be closed by calling `hostfxr_close`. This function can be called multiple times in a process. * If it's called when no runtime is present, it will run through the steps to "initialize" the runtime (resolving frameworks and so on). * If it's called when there already is CoreCLR in the process (loaded through the `hostfxr`, direct usage of `coreclr` is not supported), then the function determines if the specified runtime configuration is compatible with the existing runtime and frameworks. If it is, it returns a valid handle, otherwise it fails. It needs to be possible to call this function simultaneously from multiple threads at the same time. It also needs to be possible to call this function while there is an active host context created by `hostfxr_initialize_for_dotnet_command_line` and running inside the `hostfxr_run_app`. The function returns specific return code for the first initialized host context, and a different one for any subsequent one. Both return codes are considered "success". If there already was initialized host context in the process then the returned host context has these limitations: * It won't allow setting runtime properties. * The initialization will compare the runtime properties from the `.runtimeconfig.json` specified in the `runtime_config_path` with those already set to the runtime in the process * If all properties from the new runtime config are already set and have the exact same values (case sensitive string comparison), the initialization succeeds with no additional consequences. (Note that this is the most typical case where the runtime config have no properties in it.) * If there are either new properties which are not set in the runtime or ones which have different values, the initialization will return a special return code - a "warning". It's not a full on failure as initialized context will be returned. * In both cases only the properties specified by the new runtime config will be reported on the host context. This is to allow the native host to decide in the "warning" case if it's OK to let the component run or not. * In both cases the returned host context can still be used to get a runtime delegate, the properties from the new runtime config will be ignored (as there's no way to modify those in the runtime). The specified `.runtimeconfig.json` must be for a framework dependent component. That is it must specify at least one shared framework in its `frameworks` section. Self-contained components are not supported. ### Inspect and modify host context #### Runtime properties These functions allow the native host to inspect and modify runtime properties. * If the `host_context_handle` represents the first initialized context in the process, these functions expose all properties from runtime configurations as well as those computed by the hosting components. These functions will allow modification of the properties via `hostfxr_set_runtime_property_value`. * If the `host_context_handle` represents any other context (so not the first one), these functions expose only properties from runtime configuration. These functions won't allow modification of the properties. It is possible to access runtime properties of the first initialized context in the process at any time (for reading only), by specifying `NULL` as the `host_context_handle`. ``` C int hostfxr_get_runtime_property_value( const hostfxr_handle host_context_handle, const char_t * name, const char_t ** value); ``` Returns the value of a runtime property specified by its name. * `host_context_handle` - the initialized host context. If set to `NULL` the function will operate on runtime properties of the first host context in the process. * `name` - the name of the runtime property to get. Must not be `NULL`. * `value` - returns a pointer to a buffer with the property value. The buffer is owned by the host context. The caller should make a copy of it if it needs to store it for anything longer than immediate consumption. The lifetime is only guaranteed until any of the below happens: * one of the "run" methods is called on the host context * the host context is closed via `hostfxr_close` * the value of the property is changed via `hostfxr_set_runtime_property_value` Trying to get a property which doesn't exist is an error and will return an appropriate error code. We're proposing a fix in `hostpolicy` which will make sure that there are no duplicates possible after initialization (see [dotnet/core-setup#5529](https://github.com/dotnet/core-setup/issues/5529)). With that `hostfxr_get_runtime_property_value` will work always (as there can only be one value). ``` C int hostfxr_set_runtime_property_value( const hostfxr_handle host_context_handle, const char_t * name, const char_t * value); ``` Sets the value of a property. * `host_context_handle` - the initialized host context. (Must not be `NULL`) * `name` - the name of the runtime property to set. Must not be `NULL`. * `value` - the value of the property to set. If the property already has a value in the host context, this function will overwrite it. When set to `NULL` and if the property already has a value then the property is "unset" - removed from the runtime property collection. Setting properties is only supported on the first host context in the process. This is really a limitation of the runtime for which the runtime properties are immutable. Once the first host context is initialized and starts a runtime there's no way to change these properties. For now we will not consider the scenario where the host context is initialized but the runtime hasn't started yet, mainly for simplicity of implementation and lack of requirements. ``` C int hostfxr_get_runtime_properties( const hostfxr_handle host_context_handle, size_t * count, const char_t **keys, const char_t **values); ``` Returns the full set of all runtime properties for the specified host context. * `host_context_handle` - the initialized host context. If set to `NULL` the function will operate on runtime properties of the first host context in the process. * `count` - in/out parameter which must not be `NULL`. On input it specifies the size of the `keys` and `values` buffers. On output it contains the number of entries used from `keys` and `values` buffers - the number of properties returned. If the size of the buffers is too small, the function returns a specific error code and fill the `count` with the number of available properties. If `keys` or `values` is `NULL` the function ignores the input value of `count` and just returns the number of properties. * `keys` - buffer which acts as an array of pointers to buffers with keys for the runtime properties. * `values` - buffer which acts as an array of pointer to buffers with values for the runtime properties. `keys` and `values` store pointers to buffers which are owned by the host context. The caller should make a copy of it if it needs to store it for anything longer than immediate consumption. The lifetime is only guaranteed until any of the below happens: * one of the "run" methods is called on the host context * the host context is closed via `hostfxr_close` * the value or existence of any property is changed via `hostfxr_set_runtime_property_value` Note that `hostfxr_set_runtime_property_value` can remove or add new properties, so the number of properties returned is only valid as long as no properties were added/removed. ### Start the runtime #### Running an application ``` C int hostfxr_run_app(const hostfxr_handle host_context_handle); ``` Runs the application specified by the `hostfxr_initialize_for_dotnet_command_line`. It is illegal to try to use this function when the host context was initialized through any other way. * `host_context_handle` - handle to the initialized host context. The function will return only once the managed application exits. `hostfxr_run_app` cannot be used in combination with any other "run" function. It can also only be called once. #### Getting a delegate for runtime functionality ``` C int hostfxr_get_runtime_delegate(const hostfxr_handle host_context_handle, hostfxr_delegate_type type, void ** delegate); ``` Starts the runtime and returns a function pointer to specified functionality of the runtime. * `host_context_handle` - handle to the initialized host context. * `type` - the type of runtime functionality requested * `hdt_load_assembly_and_get_function_pointer` - entry point which loads an assembly (with dependencies) and returns function pointer for a specified static method. See below for details (Loading and calling managed components) * `hdt_com_activation`, `hdt_com_register`, `hdt_com_unregister` - COM activation entry-points - see [COM activation](https://github.com/dotnet/runtime/tree/main/docs/design/features/COM-activation.md) for more details. * `hdt_load_in_memory_assembly` - IJW entry-point - see [IJW activation](https://github.com/dotnet/runtime/tree/main/docs/design/features/IJW-activation.md) for more details. * `hdt_winrt_activation` **[.NET 3.\* only]** - WinRT activation entry-point - see [WinRT activation](https://github.com/dotnet/runtime/tree/main/docs/design/features/WinRT-activation.md) for more details. The delegate is not supported for .NET 5 and above. * `hdt_get_function_pointer` **[.NET 5 and above]** - entry-point which finds a managed method and returns a function pointer to it. See below for details (Calling managed function). * `delegate` - when successful, the native function pointer to the requested runtime functionality. In .NET Core 3.0 the function only works if `hostfxr_initialize_for_runtime_config` was used to initialize the host context. In .NET 5 the function also works if `hostfxr_initialize_for_dotnet_command_line` was used to initialize the host context. Also for .NET 5 it will only be allowed to request `hdt_load_assembly_and_get_function_pointer` or `hdt_get_function_pointer` on a context initialized via `hostfxr_initialize_for_dotnet_command_line`, all other runtime delegates will not be supported in this case. ### Cleanup ``` C int hostfxr_close(const hostfxr_handle host_context_handle); ``` Closes a host context. * `host_context_handle` - handle to the initialized host context to close. ### Loading and calling managed components To load managed components from native app directly (not using COM or WinRT) the hosting components exposes a new runtime helper/delegate `hdt_load_assembly_and_get_function_pointer`. Calling the `hostfxr_get_runtime_delegate(handle, hdt_load_assembly_and_get_function_pointer, &helper)` returns a function pointer to the runtime helper with this signature: ```C int load_assembly_and_get_function_pointer_fn( const char_t *assembly_path, const char_t *type_name, const char_t *method_name, const char_t *delegate_type_name, void *reserved, /*out*/ void **delegate) ``` Calling this function will load the specified assembly in isolation (into its own `AssemblyLoadContext`) and it will use `AssemblyDependencyResolver` on it to provide dependency resolution. Once loaded it will find the specified type and method and return a native function pointer to that method. The method's signature can be specified via the delegate type name. * `assembly_path` - Path to the assembly to load. In case of complex component, this should be the main assembly of the component (the one with the `.deps.json` next to it). Note that this does not have to be the assembly from which the `type_name` and `method_name` are. * `type_name` - Assembly qualified type name to find * `method_name` - Name of the method on the `type_name` to find. The method must be `static` and must match the signature of `delegate_type_name`. * `delegate_type_name` - Assembly qualified delegate type name for the method signature, or null. If this is null, the method signature is assumed to be: ```C# public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes); ``` This maps to native signature: ```C int component_entry_point_fn(void *arg, int32_t arg_size_in_bytes); ``` **[.NET 5 and above]** The `delegate_type_name` can be also specified as `UNMANAGEDCALLERSONLY_METHOD` (defined as `(const char_t*)-1`) which means that the managed method is marked with `UnmanagedCallersOnlyAttribute`. * `reserved` - parameter reserved for future extensibility, currently unused and must be `NULL`. * `delegate` - out parameter which receives the native function pointer to the requested managed method. The helper will always load the assembly into an isolated load context. This is the case regardless if the requested assembly is also available in the default load context or not. **[.NET 5 and above]** It is allowed to call this helper on a host context which came from `hostfxr_initialize_for_dotnet_command_line` which will make all the application assemblies available in the default load context. In such case it is recommended to only use this helper for loading plugins external to the application. Using the helper to load assembly from the application itself will lead to duplicate copies of assemblies and duplicate types. It is allowed to call the returned runtime helper many times for different assemblies or different methods from the same assembly. It is not required to get the helper every time. The implementation of the helper will cache loaded assemblies, so requests to load the same assembly twice will load it only once and reuse it from that point onward. Ideally components should not take a dependency on this behavior, which means components should not have global state. Global state in components is typically just cause for problems. For example it may create ordering issues or unintended side effects and so on. The returned native function pointer to managed method has the lifetime of the process and can be used to call the method many times over. Currently there's no way to unload the managed component or otherwise free the native function pointer. Such support may come in future releases. ### Calling managed function **[.NET 5 and above]** In .NET 5 the hosting components add a new functionality which allows just getting a native function pointer for already available managed method. This is implemented in a runtime helper `hdt_get_function_pointer`. Calling the `hostfxr_get_runtime_delegate(handle, hdt_get_function_pointer, &helper)` returns a function pointer to the runtime helper with this signature: ```C int get_function_pointer_fn( const char_t *type_name, const char_t *method_name, const char_t *delegate_type_name, void *load_context, void *reserved, /*out*/ void **delegate) ``` Calling this function will find the specified type in the default load context, locate the required method on it and return a native function pointer to that method. The method's signature can be specified via the delegate type name. * `type_name` - Assembly qualified type name to find * `method_name` - Name of the method on the `type_name` to find. The method must be `static` and must match the signature of `delegate_type_name`. * `delegate_type_name` - Assembly qualified delegate type name for the method signature, or null. If this is null, the method signature is assumed to be: ```C# public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes); ``` This maps to native signature: ```C int component_entry_point_fn(void *arg, int32_t arg_size_in_bytes); ``` The `delegate_type_name` can be also specified as `UNMANAGEDCALLERSONLY_METHOD` (defined as `(const char_t*)-1`) which means that the managed method is marked with `UnmanagedCallersOnlyAttribute`. * `load_context` - eventually this parameter should support specifying which load context should be used to locate the type/method specified in previous parameters. For .NET 5 this parameter must be `NULL` and the API will only locate the type/method in the default load context. * `reserved` - parameter reserved for future extensibility, currently unused and must be `NULL`. * `delegate` - out parameter which receives the native function pointer to the requested managed method. The helper will lookup the `type_name` from the default load context (`AssemblyLoadContext.Default`) and then return method on it. If the type and method lookup requires assemblies which have not been loaded by the Default ALC yet, this process will resolve them against the Default ALC and load them there (most likely from TPA). This helper will not register any additional assembly resolution logic onto the Default ALC, it will solely rely on the existing functionality of the Default ALC. It is allowed to ask for this helper on any valid host context. Because the helper operates on default load context only it should mostly be used with context initialized via `hostfxr_initialize_for_dotnet_command_line` as in that case the default load context will have the application code available in it. Contexts initialized via `hostfxr_initialize_for_runtime_config` have only the framework assemblies available in the default load context. The `type_name` must resolve within the default load context, so in the case where only framework assemblies are loaded into the default load context it would have to come from one of the framework assemblies only. It is allowed to call the returned runtime helper many times for different types or methods. It is not required to get the helper every time. The returned native function pointer to managed method has the lifetime of the process and can be used to call the method many times over. Currently there's no way to "release" the native function pointer (and the respective managed delegate), this functionality may be added in a future release. ### Multiple host contexts interactions It is important to correctly synchronize some of these operations to achieve the desired API behavior as well as thread safety requirements. The following behaviors will be used to achieve this. #### Terminology * `first host context` is the one which is used to load and initialize the CoreCLR runtime in the process. At any given time there can only be one `first host context`. * `secondary host context` is any other initialized host context when `first host context` already exists in the process. #### Synchronization * If there's no `first host context` in the process the first call to `hostfxr_initialize_...` will create a new `first host context`. There can only be one `first host context` in existence at any point in time. * Calling `hostfxr_initialize...` when `first host context` already exists will always return a `secondary host context`. * The `first host context` blocks creation of any other host context until it is used to load and initialize the CoreCLR runtime. This means that `hostfxr_initialize...` and subsequently one of the "run" methods must be called on the `first host context` to unblock creation of `secondary host contexts`. * Calling `hostfxr_initialize...` will block until the `first host context` is initialized, a "run" method is called on it and the CoreCLR is loaded and initialized. The `hostfxr_initialize...` will block potentially indefinitely. The method will block very early on. All of the operations done by the initialize will only happen once it's unblocked. * `first host context` can fail to initialize the runtime (or anywhere up to that point). If this happens, it's marked as failed and is not considered a `first host context` anymore. This unblocks the potentially waiting `hostfxr_initialize...` calls. In this case the first `hostfxr_initialize...` after the failure will create a new `first host context`. * `first host context` can be closed using `hostfxr_close` before it is used to initialize the CoreCLR runtime. This is similar to the failure above, the host context is marked as "closed/failed" and is not considered `first host context` anymore. This unblocks any waiting `hostfxr_initialize...` calls. * Once the `first host context` successfully initialized the CoreCLR runtime it is permanently marked as "successful" and will remain the `first host context` for the lifetime of the process. Such host context should still be closed once not needed via `hostfxr_close`. #### Invalid usage * It is invalid to initialize a host context via `hostfxr_initialize...` and then never call `hostfxr_close` on it. An initialized but not closed host context is considered abandoned. Abandoned `first host context` will cause infinite blocking of any future `hostfxr_initialize...` calls. #### Important scenarios The above behaviors should make sure that some important scenarios are possible and work reliably. One such scenario is a COM host on multiple threads. The app is not running any .NET Core yet (no CoreCLR loaded). On two threads in parallel COM activation is invoked which leads to two invocations into the `comhost` to active .NET Core objects. The `comhost` will use the `hostfxr_initialize...` and `hostfxr_get_runtime_delegate` APIs on two threads in parallel then. Only one of them can load and initialize the runtime (and also perform full framework resolution and determine the framework versions and assemblies to load). The other has to become a `secondary host context` and try to conform to the first one. The above behavior of `hostfxr_initialize...` blocking until the `first host context` is done initializing the runtime will make sure of the correct behavior in this case. At the same time it gives the native app (`comhost` in this case) the ability to query and modify runtime properties in between the `hostfxr_initialize...` and `hostfxr_get_runtime_delegate` calls on the `first host context`. ### API usage The `hostfxr` exports are defined in the [hostfxr.h](https://github.com/dotnet/runtime/blob/main/src/native/corehost/hostfxr.h) header file. The runtime helper and method signatures for loading managed components are defined in [coreclr_delegates.h](https://github.com/dotnet/runtime/blob/main/src/native/corehost/coreclr_delegates.h) header file. Currently we don't plan to ship these files, but it's possible to take them from the repo and use it. ### Support for older versions Since `hostfxr` and the other hosting components are versioned independently there are several interesting cases of version mismatches: #### muxer/`apphost` versus `hostfxr` For muxer it should almost always match, but `apphost` can be different. That is, it's perfectly valid to use older 2.* `apphost` with a new 3.0 `hostfxr`. The opposite should be rare, but in theory can happen as well. To keep the code simple both muxer and `apphost` will keep using the existing 2.* APIs on `hostfxr` even in situation where both are 3.0 and thus could start using the new APIs. `hostfxr` must be backward compatible and support 2.* APIs. Potentially we could switch just `apphost` to use the new APIs (since it doesn't have the same compatibility burden as the muxer), but it's probably safer to not do that. #### `hostfxr` versus `hostpolicy` It should really only happen that `hostfxr` is equal or newer than `hostpolicy`. The opposite should be very rare. In any case `hostpolicy` should support existing 2.* APIs and thus the rare case will keep working anyway. The interesting case is 3.0 `hostfxr` using 2.* `hostpolicy`. This will be very common, basically any 2.* app running on a machine with 3.0 installed will be in that situation. This case has two sub-cases: * `hostfxr` is invoked using one of the 2.* APIs. In this case the simple solution is to keep using the 2.* `hostpolicy` APIs always. * `hostfxr` is invoked using one of the new 3.0 APIs (like `hostfxr_initialize...`). In this case it's not possible to completely support the new APIs, since they require new functionality from `hostpolicy`. For now the `hostfxr` should simply fail. It is in theory possible to support some kind of emulation mode where for some scenarios the new APIs would work even with old `hostpolicy`, but for simplicity it's better to start with just failing. #### Implementation of existing 2.* APIs in `hostfxr` The existing 2.* APIs in `hostfxr` could switch to internally use the new functionality and in turn use the new 3.0 `hostpolicy` APIs. The tricky bit here is scenario like this: * 3.0 App is started via `apphost` or muxer which as mentioned above will keep on using the 2.* `hostfxr` APIs. This will load CoreCLR into the process. * COM component is activated in the same process. This will go through the new 3.0 `hostfxr` APIs, and to work correctly will require the internal representation of the `first host context`. If the 2.* `hostfxr` APIs would continue to use the old 2.* `hostpolicy` APIs even if `hostpolicy` is new, then the above scenario will be hard to achieve as there will be no `first host context`. `hostpolicy` could somehow "emulate" the `first host context`, but without `hostpolicy` cooperation this would be hard. On the other hand switching to use the new `hostpolicy` APIs even in 2.* `hostfxr` APIs is risky for backward compatibility. This will have to be decided during implementation. ### Samples All samples assume that the native host has found the `hostfxr`, loaded it and got the exports (possibly by using the `nethost`). Samples in general ignore error handling. #### Running app with additional runtime properties ``` C++ hostfxr_initialize_parameters params; params.size = sizeof(params); params.host_path = get_path_to_the_host_exe(); // Path to the current executable params.dotnet_root = get_directory(get_directory(get_directory(hostfxr_path))); // Three levels up from hostfxr typically hostfxr_handle host_context_handle; hostfxr_initialize_for_dotnet_command_line( _argc_, _argv_, // For example, 'app.dll app_argument_1 app_argument_2' &params, &host_context_handle); size_t buffer_used = 0; if (hostfxr_get_runtime_property(host_context_handle, "TEST_PROPERTY", NULL, 0, &buffer_used) == HostApiMissingProperty) { hostfxr_set_runtime_property(host_context_handle, "TEST_PROPERTY", "TRUE"); } hostfxr_run_app(host_context_handle); hostfxr_close(host_context_handle); ``` #### Getting a function pointer to call a managed method ```C++ using load_assembly_and_get_function_pointer_fn = int (STDMETHODCALLTYPE *)( const char_t *assembly_path, const char_t *type_name, const char_t *method_name, const char_t *delegate_type_name, void *reserved, void **delegate); hostfxr_handle host_context_handle; hostfxr_initialize_for_runtime_config(config_path, NULL, &host_context_handle); load_assembly_and_get_function_pointer_fn runtime_delegate = NULL; hostfxr_get_runtime_delegate( host_context_handle, hostfxr_delegate_type::load_assembly_and_get_function_pointer, (void **)&runtime_delegate); using managed_entry_point_fn = int (STDMETHODCALLTYPE *)(void *arg, int argSize); managed_entry_point_fn entry_point = NULL; runtime_delegate(assembly_path, type_name, method_name, NULL, NULL, (void **)&entry_point); ArgStruct arg; entry_point(&arg, sizeof(ArgStruct)); hostfxr_close(host_context_handle); ``` ## Impact on hosting components The exact impact on the `hostfxr`/`hostpolicy` interface needs to be investigated. The assumption is that new APIs will have to be added to `hostpolicy` to implement the proposed functionality. Part if this investigation will also be compatibility behavior. Currently "any" version of `hostfxr` needs to be able to use "any" version of `hostpolicy`. But the proposed functionality will need both new `hostfxr` and new `hostpolicy` to work. It is likely the proposed APIs will fail if the app resolves to a framework with old `hostpolicy` without the necessary new APIs. Part of the investigation will be if it's feasible to use the new `hostpolicy` APIs to implement existing old `hostfxr` APIs. ## Incompatible with trimming Native hosting support on managed side is disabled by default on trimmed apps. Native hosting and trimming are incompatible since the trimmer cannot analyze methods that are called by native hosts. Native hosting support for trimming can be managed through the [feature switch](https://github.com/dotnet/runtime/blob/main/docs/workflow/trimming/feature-switches.md) settings specific to each native host.
# Native hosting Native hosting is the ability to host the .NET runtime in an arbitrary process, one which didn't start from .NET Core produced binaries. #### Terminology * "native host" - the code which uses the proposed APIs. Can be any non .NET Core application (.NET Core applications have easier ways to perform these scenarios). * "hosting components" - shorthand for .NET Core hosting components. Typically refers to `hostfxr` and `hostpolicy`. Sometimes also referred to simply as "host". * "host context" - state which `hostfxr` creates and maintains and represents a logical operation on the hosting components. ## Scenarios * **Hosting managed components** Native host which wants to load managed assembly and call into it for some functionality. Must support loading multiple such components side by side. * **Hosting managed apps** Native host which wants to run a managed app in-proc. Basically a different implementation of the existing .NET Core hosts (`dotnet.exe` or `apphost`). The intent is the ability to modify how the runtime starts and how the managed app is executed (and where it starts from). * **App using other .NET Core hosting services** App (native or .NET Core both) which needs to use some of the other services provided by the .NET Core hosting components. For example the ability to locate available SDKs and so on. ## Existing support * **C-style ABI in `coreclr`** `coreclr` exposes ABI to host the .NET runtime and run managed code already using C-style APIs. See this [header file](https://github.com/dotnet/runtime/blob/main/src/coreclr/hosts/inc/coreclrhost.h) for the exposed functions. This API requires the native host to locate the runtime and to fully specify all startup parameters for the runtime. There's no inherent interoperability between these APIs and the .NET SDK. * **COM-style ABI in `coreclr`** `coreclr` exposes COM-style ABI to host the .NET runtime and perform a wide range of operations on it. See this [header file](https://github.com/dotnet/runtime/blob/main/src/coreclr/pal/prebuilt/inc/mscoree.h) for more details. Similarly to the C-style ABI the COM-style ABI also requires the native host to locate the runtime and to fully specify all startup parameters. There's no inherent interoperability between these APIs and the .NET SDK. The COM-style ABI is deprecated and should not be used going forward. * **`hostfxr` and `hostpolicy` APIs** The hosting components of .NET Core already exposes some functionality as C-style ABI on either the `hostfxr` or `hostpolicy` libraries. These can execute application, determine available SDKs, determine native dependency locations, resolve component dependencies and so on. Unlike the above `coreclr` based APIs these don't require the caller to fully specify all startup parameters, instead these APIs understand artifacts produced by .NET SDK making it much easier to consume SDK produced apps/libraries. The native host is still required to locate the `hostfxr` or `hostpolicy` libraries. These APIs are also designed for specific narrow scenarios, any usage outside of these bounds is typically not possible. ## Scope This document focuses on hosting which cooperates with the .NET SDK and consumes the artifacts produced by building the managed app/libraries directly. It completely ignores the COM-style ABI as it's hard to use from some programming languages. As such the document explicitly excludes any hosting based on directly loading `coreclr`. Instead it focuses on using the existing .NET Core hosting components in new ways. For details on the .NET Core hosting components see [this document](https://github.com/dotnet/runtime/tree/main/docs/design/features/host-components.md). ## Longer term vision This section describes how we think the hosting components should evolve. It is expected that this won't happen in any single release, but each change should fit into this picture and hopefully move us closer to this goal. It is also expected that existing APIs won't change (no breaking changes) and thus it can happen that some of the APIs don't fit nicely into the picture. The hosting component APIs should provide functionality to cover a wide range of applications. At the same time it needs to stay in sync with what .NET Core SDK can produce so that the end-to-end experience is available. The overall goal of hosting components is to enable loading and executing managed code, this consists of four main steps: * **Locate and load hosting components** - How does a native host find and load the hosting components libraries. * **Locate the managed code and all its dependencies** - Determining where the managed code comes from (application, component, ...), what frameworks it relies on (framework resolution) and what dependencies it needs (`.deps.json` processing) * **Load the managed code into the process** - Specify the environment and settings for the runtime, locating or starting the runtime, deciding how to load the managed code into the runtime (which `AssemblyLoadContext` for example) and actually loading the managed code and its dependencies. * **Accessing and executing managed code** - Locate the managed entry point (for example assembly entry point `Main`, or a specific method to call, or some other means to transition control to the managed code) and exposing it into the native code (function pointer, COM interface, direct execution, ...). To achieve these we will structure the hosting components APIs into similar (but not exactly) 4 buckets. ### Locating hosting components This means providing APIs to find and load the hosting components. The end result should be that the native host has the right version of `hostfxr` loaded and can call its APIs. The exact solution is dependent on the native host application and its tooling. Ideally we would have a solution which works great for several common environments like C/C++ apps built in VS, C/C++ apps on Mac/Linux built with CMake (or similar) and so on. First step in this direction is the introduction of `nethost` library described below. ### Initializing host context The end result of this step should be an initialized host context for a given managed code input which the native host can use to load the managed code and execute it. The step should not actually load any runtime or managed code into the process. Finally this step must handle both processes which don't have any runtime loaded as well as processes which already have runtime loaded. Functionality performed by this step: * Locating and understanding the managed code input (app/component) * Resolving frameworks or handling self-contained * Resolving dependencies (`.deps.json` processing) * Populating runtime properties The vision is to expose a set of APIs in the form of `hostfxr_initialize_for_...` which would all perform the above functionality and would differ on how the managed code is located and used. So there should be a different API for loading applications and components at the very least. Going forward we can add API which can initialize the context from in-memory configurations, or API which can initialize an "empty" context (no custom code involved, just frameworks) and so on. First step in this direction is the introduction of these APIs as described below: * `hostfxr_initialize_for_dotnet_command_line` - this is the initialize for an application. The API is a bit more complicated as it allows for command line parsing as well. Eventually we might want to add another "initialize app" API without the command line support. * `hostfxr_initialize_for_runtime_config` - this is the initialize for a component (naming is not ideal, but can't be changed anymore). After this step it should be possible for the native host to inspect and potentially modify runtime properties. APIs like `hostfxr_get_runtime_property_value` and similar described below are an example of this. ### Loading managed code This step might be "virtual" in the sense that it's a way to setup the context for the desired functionality. In several scenarios it's not practical to be able to perform this step in separation from the "execute code" step below. The goal of this step is to determine which managed code to load, where it should be loaded into, and to setup the correct inputs so that runtime can perform the right dependency resolution. Logically this step finds/loads the runtime and initializes it before it can load any managed code into the process. The main flexibility this step should provide is to determine which assembly load context will be used for loading which code: * Load all managed code into the default load context * Load the specified custom managed code into an isolated load context Eventually we could also add functionality for example to setup the isolated load context for unloadability and so on. Note that there are no APIs proposed in this document which would only perform this step for now. All the APIs so far fold this step into the next one and perform both loading and executing of the managed code in one step. We should try to make this step more explicit in the future to allow for greater flexibility. After this step it is no longer possible to modify runtime properties (inspection is still allowed) since the runtime has been loaded. ### Accessing and executing managed code The end result of this step is either execution of the desired managed code, or returning a native callable representation of the managed code. The different options should include at least: * running an application (where the API takes over the thread and runs the application on behalf of the calling thread) - the `hostfxr_run_app` API described bellow is an example of this. * getting a native function pointer to a managed method - the `hostfxr_get_runtime_delegate` and the `hdt_load_assembly_and_get_function_pointer` described below is an example of this. * getting a native callable interface (COM) to a managed instance - the `hostfxr_get_runtime_delegate` and the `hdt_com_activation` described below is an example of this. * and more... ### Combinations Ideally it should be possible to combine the different types of initialization, loading and executing of managed code in any way the native host desires. In reality not all combinations are possible or practical. Few examples of combinations which we should probably NOT support (note that this may change in the future): * running a component as an application - runtime currently makes too many assumptions on what it means to "Run an application" * loading application into an isolated load context - for now there are too many limitations in the frameworks around secondary load contexts (several large framework features don't work well in a secondary ALC), so the hosting components should prevent this as a way to prevent users from getting into a bad situation. * loading multiple copies of the runtime into the process - support for side-by-side loading of different .NET Core runtime in a single process is not something we want to implement (at least yet). Hosting components should not allow this to make the user experience predictable. This means that full support for loading self-contained components at all times is not supported. Lot of other combinations will not be allowed simply as a result of shipping decisions. There's only so much functionality we can fit into any given release, so many combinations will be explicitly disabled to reduce the work necessary to actually ship this. The document below should describe which combinations are allowed in which release. ## High-level proposal In .NET Core 3.0 the hosting components (see [here](https://github.com/dotnet/runtime/tree/main/docs/design/features/host-components.md)) ships with several hosts. These are binaries which act as the entry points to the .NET Core hosting components/runtime: * The "muxer" (`dotnet.exe`) * The `apphost` (`.exe` which is part of the app) * The `comhost` (`.dll` which is part of the app and acts as COM server) * The `ijwhost` (`.dll` consumed via `.lib` used by IJW assemblies) Every one of these hosts serve different scenario and expose different APIs. The one thing they have in common is that their main purpose is to find the right `hostfxr`, load it and call into it to execute the desired scenario. For the most part all these hosts are basically just wrappers around functionality provided by `hostfxr`. The proposal is to add a new host library `nethost` which can be used by native host to easily locate `hostfxr`. Going forward the library could also include easy-to-use APIs for common scenarios - basically just a simplification of the `hostfxr` API surface. At the same time add the ability to pass additional runtime properties when starting the runtime through the hosting components APIs (starting app, loading component). This can be used by the native host to: * Register startup hook without modifying environment variables (which are inherited by child processes) * Introduce new runtime knobs which are only available for native hosts without the need to update the hosting components APIs every time. *Technical note: All strings in the proposed APIs are using the `char_t` in this document for simplicity. In real implementation they are of the type `pal::char_t`. In particular:* * *On Windows - they are `WCHAR *` using `UTF16` encoding* * *On Linux/macOS - they are `char *` using `UTF8` encoding* ## New host binary for finding `hostfxr` New library `nethost` which provides a way to locate the right `hostfxr`. This is a dynamically loaded library (`.dll`, `.so`, `.dylib`). For ease of use there is a header file for C/C++ apps as well as `.lib` for easy linking on Windows. Native hosts ship this library as part of the app. Unlike the `apphost`, `comhost` and `ijwhost`, the `nethost` will not be directly supported by the .NET SDK since it's target usage is not from .NET Core apps. The `nethost` is part of the `Microsoft.NETCore.DotNetAppHost` package. Users are expected to either download the package directly or rely on .NET SDK to pull it down. The binary itself should be signed by Microsoft as there will be no support for modifying the binary as part of custom application build (unlike `apphost`). ### Locate `hostfxr` ``` C++ struct get_hostfxr_parameters { size_t size; const char_t * assembly_path; const char_t * dotnet_root; }; int get_hostfxr_path( char_t * result_buffer, size_t * buffer_size, const get_hostfxr_parameters * parameters); ``` This API locates the `hostfxr` library and returns its path by populating `result_buffer`. * `result_buffer` - Buffer that will be populated with the hostfxr path, including a null terminator. * `buffer_size` - On input this points to the size of the `result_buffer` in `char_t` units. On output this points to the number of `char_t` units used from the `result_buffer` (including the null terminator). If `result_buffer` is `NULL` the input value is ignored and only the minimum required size in `char_t` units is set on output. * `parameters` - Optional. Additional parameters that modify the behaviour for locating the `hostfxr` library. If `NULL`, `hostfxr` is located using the environment variable or global registration * `size` - Size of the structure. This is used for versioning and should be set to `sizeof(get_hostfxr_parameters)`. * `assembly_path` - Optional. Path to the application or to the component's assembly. * If specified, `hostfxr` is located as if the `assembly_path` is an application with `apphost` * `dotnet_root` - Optional. Path to the root of a .NET Core installation (i.e. folder containing the dotnet executable). * If specified, `hostfxr` is located as if an application is started using `dotnet app.dll`, which means it will be searched for under the `dotnet_root` path and the `assembly_path` is ignored. `nethost` library uses the `__stdcall` calling convention. ## Improve API to run application and load components ### Goals * All hosts should be able to use the new API (whether they will is a separate question as the old API has to be kept for backward compat reasons) * Hide implementation details as much as possible * Make the API generally easier to use/understand * Give the implementation more freedom * Allow future improvements without breaking the API * Consider explicitly documenting types of behaviors which nobody should take dependency on (specifically failure scenarios) * Extensible * It should allow additional parameters to some of the operations without a need to add new exported APIs * It should allow additional interactions with the host - for example modifying how the runtime is initialized via some new options, without a need for a completely new set of APIs ### New scenarios The API should allow these scenarios: * Runtime properties * Specify additional runtime properties from the native host * Implement conflict resolution for runtime properties * Inspect calculated runtime properties (the ones calculated by `hostfxr`/`hostpolicy`) * Load managed component and get native function pointer for managed method * From native app start the runtime and load an assembly * The assembly is loaded in isolation and with all its dependencies as directed by `.deps.json` * The native app can get back a native function pointer which calls specified managed method * Get native function pointer for managed method * From native code get a native function pointer to already loaded managed method All the proposed APIs will be exports of the `hostfxr` library and will use the same calling convention and name mangling as existing `hostfxr` exports. ### Initialize host context All the "initialize" functions will * Process the `.runtimeconfig.json` * Resolve framework references and find actual frameworks * Find the root framework (`Microsoft.NETCore.App`) and load the `hostpolicy` from it * The `hostpolicy` will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. The functions will NOT load the CoreCLR runtime. They just prepare everything to the point where it can be loaded. The functions return a handle to a new host context: * The handle must be closed via `hostfxr_close`. * The handle is not thread safe - the consumer should only call functions on it from one thread at a time. The `hostfxr` will also track active runtime in the process. Due to limitations (and to simplify implementation) this tracking will actually not look at the actual `coreclr` module (or try to communicate with the runtime in any way). Instead `hostfxr` itself will track the host context initialization. The first host context initialization in the process will represent the "loaded runtime". It is only possible to have one "loaded runtime" in the process. Any subsequent host context initialization will just "attach" to the "loaded runtime" instead of creating a new one. ``` C typedef void* hostfxr_handle; struct hostfxr_initialize_parameters { size_t size; const char_t * host_path; const char_t * dotnet_root; }; ``` The `hostfxr_initialize_parameters` structure stores parameters which are common to all forms of initialization. * `size` - the size of the structure. This is used for versioning. Should be set to `sizeof(hostfxr_initialize_parameters)`. * `host_path` - path to the native host (typically the `.exe`). This value is not used for anything by the hosting components. It's just passed to the CoreCLR as the path to the executable. It can point to a file which is not executable itself, if such file doesn't exist (for example in COM activation scenarios this points to the `comhost.dll`). This is used by PAL to initialize internal command line structures, process name and so on. * `dotnet_root` - path to the root of the .NET Core installation in use. This typically points to the install location from which the `hostfxr` has been loaded. For example on Windows this would typically point to `C:\Program Files\dotnet`. The path is used to search for shared frameworks and potentially SDKs. ``` C int hostfxr_initialize_for_dotnet_command_line( int argc, const char_t * argv[], const hostfxr_initialize_parameters * parameters, hostfxr_handle * host_context_handle ); ``` Initializes the hosting components for running a managed application. The command line is parsed to determine the app path. The app path will be used to locate the `.runtimeconfig.json` and the `.deps.json` which will be used to load the application and its dependent frameworks. * `argc` and `argv` - the command line for running a managed application. These represent the arguments which would have been passed to the muxer if the app was being run from the command line. These are the parameters which are valid for the runtime installation by itself - SDK/CLI commands are not supported. For example, the arguments could be `app.dll app_argument_1 app_argument_2`. This API specifically doesn't support the `dotnet run` SDK command. * `parameters` - additional parameters - see `hostfxr_initialize_parameters` for details. (Could be made optional potentially) * `host_context_handle` - output parameter. On success receives an opaque value which identifies the initialized host context. The handle should be closed by calling `hostfxr_close`. This function only supports arguments for running an application as through the muxer. It does not support SDK commands. This function can only be called once per-process. It's not supported to run multiple apps in one process (even sequentially). This function will fail if there already is a CoreCLR running in the process as it's not possible to run two apps in a single process. This function supports both framework-dependent and self-contained applications. *Note: This is effectively a replacement for `hostfxr_main_startupinfo` and `hostfxr_main`. Currently it is not a goal to fully replace these APIs because they also support SDK commands which are special in lot of ways and don't fit well with the rest of the native hosting. There's no scenario right now which would require the ability to issue SDK commands from a native host. That said nothing in this proposal should block enabling even SDK commands through these APIs.* ``` C int hostfxr_initialize_for_runtime_config( const char_t * runtime_config_path, const hostfxr_initialize_parameters * parameters, hostfxr_handle * host_context_handle ); ``` This function would load the specified `.runtimeconfig.json`, resolve all frameworks, resolve all the assets from those frameworks and then prepare runtime initialization where the TPA contains only frameworks. Note that this case does NOT consume any `.deps.json` from the app/component (only processes the framework's `.deps.json`). This entry point is intended for `comhost`/`ijwhost`/`nethost` and similar scenarios. * `runtime_config_path` - path to the `.runtimeconfig.json` file to process. Unlike with `hostfxr_initialize_for_dotnet_command_line`, any `.deps.json` from the app/component will not be processed by the hosting components during the initialize call. * `parameters` - additional parameters - see `hostfxr_initialize_parameters` for details. (Could be made optional potentially) * `host_context_handle` - output parameter. On success receives an opaque value which identifies the initialized host context. The handle should be closed by calling `hostfxr_close`. This function can be called multiple times in a process. * If it's called when no runtime is present, it will run through the steps to "initialize" the runtime (resolving frameworks and so on). * If it's called when there already is CoreCLR in the process (loaded through the `hostfxr`, direct usage of `coreclr` is not supported), then the function determines if the specified runtime configuration is compatible with the existing runtime and frameworks. If it is, it returns a valid handle, otherwise it fails. It needs to be possible to call this function simultaneously from multiple threads at the same time. It also needs to be possible to call this function while there is an active host context created by `hostfxr_initialize_for_dotnet_command_line` and running inside the `hostfxr_run_app`. The function returns specific return code for the first initialized host context, and a different one for any subsequent one. Both return codes are considered "success". If there already was initialized host context in the process then the returned host context has these limitations: * It won't allow setting runtime properties. * The initialization will compare the runtime properties from the `.runtimeconfig.json` specified in the `runtime_config_path` with those already set to the runtime in the process * If all properties from the new runtime config are already set and have the exact same values (case sensitive string comparison), the initialization succeeds with no additional consequences. (Note that this is the most typical case where the runtime config have no properties in it.) * If there are either new properties which are not set in the runtime or ones which have different values, the initialization will return a special return code - a "warning". It's not a full on failure as initialized context will be returned. * In both cases only the properties specified by the new runtime config will be reported on the host context. This is to allow the native host to decide in the "warning" case if it's OK to let the component run or not. * In both cases the returned host context can still be used to get a runtime delegate, the properties from the new runtime config will be ignored (as there's no way to modify those in the runtime). The specified `.runtimeconfig.json` must be for a framework dependent component. That is it must specify at least one shared framework in its `frameworks` section. Self-contained components are not supported. ### Inspect and modify host context #### Runtime properties These functions allow the native host to inspect and modify runtime properties. * If the `host_context_handle` represents the first initialized context in the process, these functions expose all properties from runtime configurations as well as those computed by the hosting components. These functions will allow modification of the properties via `hostfxr_set_runtime_property_value`. * If the `host_context_handle` represents any other context (so not the first one), these functions expose only properties from runtime configuration. These functions won't allow modification of the properties. It is possible to access runtime properties of the first initialized context in the process at any time (for reading only), by specifying `NULL` as the `host_context_handle`. ``` C int hostfxr_get_runtime_property_value( const hostfxr_handle host_context_handle, const char_t * name, const char_t ** value); ``` Returns the value of a runtime property specified by its name. * `host_context_handle` - the initialized host context. If set to `NULL` the function will operate on runtime properties of the first host context in the process. * `name` - the name of the runtime property to get. Must not be `NULL`. * `value` - returns a pointer to a buffer with the property value. The buffer is owned by the host context. The caller should make a copy of it if it needs to store it for anything longer than immediate consumption. The lifetime is only guaranteed until any of the below happens: * one of the "run" methods is called on the host context * the host context is closed via `hostfxr_close` * the value of the property is changed via `hostfxr_set_runtime_property_value` Trying to get a property which doesn't exist is an error and will return an appropriate error code. We're proposing a fix in `hostpolicy` which will make sure that there are no duplicates possible after initialization (see [dotnet/core-setup#5529](https://github.com/dotnet/core-setup/issues/5529)). With that `hostfxr_get_runtime_property_value` will work always (as there can only be one value). ``` C int hostfxr_set_runtime_property_value( const hostfxr_handle host_context_handle, const char_t * name, const char_t * value); ``` Sets the value of a property. * `host_context_handle` - the initialized host context. (Must not be `NULL`) * `name` - the name of the runtime property to set. Must not be `NULL`. * `value` - the value of the property to set. If the property already has a value in the host context, this function will overwrite it. When set to `NULL` and if the property already has a value then the property is "unset" - removed from the runtime property collection. Setting properties is only supported on the first host context in the process. This is really a limitation of the runtime for which the runtime properties are immutable. Once the first host context is initialized and starts a runtime there's no way to change these properties. For now we will not consider the scenario where the host context is initialized but the runtime hasn't started yet, mainly for simplicity of implementation and lack of requirements. ``` C int hostfxr_get_runtime_properties( const hostfxr_handle host_context_handle, size_t * count, const char_t **keys, const char_t **values); ``` Returns the full set of all runtime properties for the specified host context. * `host_context_handle` - the initialized host context. If set to `NULL` the function will operate on runtime properties of the first host context in the process. * `count` - in/out parameter which must not be `NULL`. On input it specifies the size of the `keys` and `values` buffers. On output it contains the number of entries used from `keys` and `values` buffers - the number of properties returned. If the size of the buffers is too small, the function returns a specific error code and fill the `count` with the number of available properties. If `keys` or `values` is `NULL` the function ignores the input value of `count` and just returns the number of properties. * `keys` - buffer which acts as an array of pointers to buffers with keys for the runtime properties. * `values` - buffer which acts as an array of pointer to buffers with values for the runtime properties. `keys` and `values` store pointers to buffers which are owned by the host context. The caller should make a copy of it if it needs to store it for anything longer than immediate consumption. The lifetime is only guaranteed until any of the below happens: * one of the "run" methods is called on the host context * the host context is closed via `hostfxr_close` * the value or existence of any property is changed via `hostfxr_set_runtime_property_value` Note that `hostfxr_set_runtime_property_value` can remove or add new properties, so the number of properties returned is only valid as long as no properties were added/removed. ### Start the runtime #### Running an application ``` C int hostfxr_run_app(const hostfxr_handle host_context_handle); ``` Runs the application specified by the `hostfxr_initialize_for_dotnet_command_line`. It is illegal to try to use this function when the host context was initialized through any other way. * `host_context_handle` - handle to the initialized host context. The function will return only once the managed application exits. `hostfxr_run_app` cannot be used in combination with any other "run" function. It can also only be called once. #### Getting a delegate for runtime functionality ``` C int hostfxr_get_runtime_delegate(const hostfxr_handle host_context_handle, hostfxr_delegate_type type, void ** delegate); ``` Starts the runtime and returns a function pointer to specified functionality of the runtime. * `host_context_handle` - handle to the initialized host context. * `type` - the type of runtime functionality requested * `hdt_load_assembly_and_get_function_pointer` - entry point which loads an assembly (with dependencies) and returns function pointer for a specified static method. See below for details (Loading and calling managed components) * `hdt_com_activation`, `hdt_com_register`, `hdt_com_unregister` - COM activation entry-points - see [COM activation](https://github.com/dotnet/runtime/tree/main/docs/design/features/COM-activation.md) for more details. * `hdt_load_in_memory_assembly` - IJW entry-point - see [IJW activation](https://github.com/dotnet/runtime/tree/main/docs/design/features/IJW-activation.md) for more details. * `hdt_winrt_activation` **[.NET 3.\* only]** - WinRT activation entry-point - see [WinRT activation](https://github.com/dotnet/runtime/tree/main/docs/design/features/WinRT-activation.md) for more details. The delegate is not supported for .NET 5 and above. * `hdt_get_function_pointer` **[.NET 5 and above]** - entry-point which finds a managed method and returns a function pointer to it. See below for details (Calling managed function). * `delegate` - when successful, the native function pointer to the requested runtime functionality. In .NET Core 3.0 the function only works if `hostfxr_initialize_for_runtime_config` was used to initialize the host context. In .NET 5 the function also works if `hostfxr_initialize_for_dotnet_command_line` was used to initialize the host context. Also for .NET 5 it will only be allowed to request `hdt_load_assembly_and_get_function_pointer` or `hdt_get_function_pointer` on a context initialized via `hostfxr_initialize_for_dotnet_command_line`, all other runtime delegates will not be supported in this case. ### Cleanup ``` C int hostfxr_close(const hostfxr_handle host_context_handle); ``` Closes a host context. * `host_context_handle` - handle to the initialized host context to close. ### Loading and calling managed components To load managed components from native app directly (not using COM or WinRT) the hosting components exposes a new runtime helper/delegate `hdt_load_assembly_and_get_function_pointer`. Calling the `hostfxr_get_runtime_delegate(handle, hdt_load_assembly_and_get_function_pointer, &helper)` returns a function pointer to the runtime helper with this signature: ```C int load_assembly_and_get_function_pointer_fn( const char_t *assembly_path, const char_t *type_name, const char_t *method_name, const char_t *delegate_type_name, void *reserved, /*out*/ void **delegate) ``` Calling this function will load the specified assembly in isolation (into its own `AssemblyLoadContext`) and it will use `AssemblyDependencyResolver` on it to provide dependency resolution. Once loaded it will find the specified type and method and return a native function pointer to that method. The method's signature can be specified via the delegate type name. * `assembly_path` - Path to the assembly to load. In case of complex component, this should be the main assembly of the component (the one with the `.deps.json` next to it). Note that this does not have to be the assembly from which the `type_name` and `method_name` are. * `type_name` - Assembly qualified type name to find * `method_name` - Name of the method on the `type_name` to find. The method must be `static` and must match the signature of `delegate_type_name`. * `delegate_type_name` - Assembly qualified delegate type name for the method signature, or null. If this is null, the method signature is assumed to be: ```C# public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes); ``` This maps to native signature: ```C int component_entry_point_fn(void *arg, int32_t arg_size_in_bytes); ``` **[.NET 5 and above]** The `delegate_type_name` can be also specified as `UNMANAGEDCALLERSONLY_METHOD` (defined as `(const char_t*)-1`) which means that the managed method is marked with `UnmanagedCallersOnlyAttribute`. * `reserved` - parameter reserved for future extensibility, currently unused and must be `NULL`. * `delegate` - out parameter which receives the native function pointer to the requested managed method. The helper will always load the assembly into an isolated load context. This is the case regardless if the requested assembly is also available in the default load context or not. **[.NET 5 and above]** It is allowed to call this helper on a host context which came from `hostfxr_initialize_for_dotnet_command_line` which will make all the application assemblies available in the default load context. In such case it is recommended to only use this helper for loading plugins external to the application. Using the helper to load assembly from the application itself will lead to duplicate copies of assemblies and duplicate types. It is allowed to call the returned runtime helper many times for different assemblies or different methods from the same assembly. It is not required to get the helper every time. The implementation of the helper will cache loaded assemblies, so requests to load the same assembly twice will load it only once and reuse it from that point onward. Ideally components should not take a dependency on this behavior, which means components should not have global state. Global state in components is typically just cause for problems. For example it may create ordering issues or unintended side effects and so on. The returned native function pointer to managed method has the lifetime of the process and can be used to call the method many times over. Currently there's no way to unload the managed component or otherwise free the native function pointer. Such support may come in future releases. ### Calling managed function **[.NET 5 and above]** In .NET 5 the hosting components add a new functionality which allows just getting a native function pointer for already available managed method. This is implemented in a runtime helper `hdt_get_function_pointer`. Calling the `hostfxr_get_runtime_delegate(handle, hdt_get_function_pointer, &helper)` returns a function pointer to the runtime helper with this signature: ```C int get_function_pointer_fn( const char_t *type_name, const char_t *method_name, const char_t *delegate_type_name, void *load_context, void *reserved, /*out*/ void **delegate) ``` Calling this function will find the specified type in the default load context, locate the required method on it and return a native function pointer to that method. The method's signature can be specified via the delegate type name. * `type_name` - Assembly qualified type name to find * `method_name` - Name of the method on the `type_name` to find. The method must be `static` and must match the signature of `delegate_type_name`. * `delegate_type_name` - Assembly qualified delegate type name for the method signature, or null. If this is null, the method signature is assumed to be: ```C# public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes); ``` This maps to native signature: ```C int component_entry_point_fn(void *arg, int32_t arg_size_in_bytes); ``` The `delegate_type_name` can be also specified as `UNMANAGEDCALLERSONLY_METHOD` (defined as `(const char_t*)-1`) which means that the managed method is marked with `UnmanagedCallersOnlyAttribute`. * `load_context` - eventually this parameter should support specifying which load context should be used to locate the type/method specified in previous parameters. For .NET 5 this parameter must be `NULL` and the API will only locate the type/method in the default load context. * `reserved` - parameter reserved for future extensibility, currently unused and must be `NULL`. * `delegate` - out parameter which receives the native function pointer to the requested managed method. The helper will lookup the `type_name` from the default load context (`AssemblyLoadContext.Default`) and then return method on it. If the type and method lookup requires assemblies which have not been loaded by the Default ALC yet, this process will resolve them against the Default ALC and load them there (most likely from TPA). This helper will not register any additional assembly resolution logic onto the Default ALC, it will solely rely on the existing functionality of the Default ALC. It is allowed to ask for this helper on any valid host context. Because the helper operates on default load context only it should mostly be used with context initialized via `hostfxr_initialize_for_dotnet_command_line` as in that case the default load context will have the application code available in it. Contexts initialized via `hostfxr_initialize_for_runtime_config` have only the framework assemblies available in the default load context. The `type_name` must resolve within the default load context, so in the case where only framework assemblies are loaded into the default load context it would have to come from one of the framework assemblies only. It is allowed to call the returned runtime helper many times for different types or methods. It is not required to get the helper every time. The returned native function pointer to managed method has the lifetime of the process and can be used to call the method many times over. Currently there's no way to "release" the native function pointer (and the respective managed delegate), this functionality may be added in a future release. ### Multiple host contexts interactions It is important to correctly synchronize some of these operations to achieve the desired API behavior as well as thread safety requirements. The following behaviors will be used to achieve this. #### Terminology * `first host context` is the one which is used to load and initialize the CoreCLR runtime in the process. At any given time there can only be one `first host context`. * `secondary host context` is any other initialized host context when `first host context` already exists in the process. #### Synchronization * If there's no `first host context` in the process the first call to `hostfxr_initialize_...` will create a new `first host context`. There can only be one `first host context` in existence at any point in time. * Calling `hostfxr_initialize...` when `first host context` already exists will always return a `secondary host context`. * The `first host context` blocks creation of any other host context until it is used to load and initialize the CoreCLR runtime. This means that `hostfxr_initialize...` and subsequently one of the "run" methods must be called on the `first host context` to unblock creation of `secondary host contexts`. * Calling `hostfxr_initialize...` will block until the `first host context` is initialized, a "run" method is called on it and the CoreCLR is loaded and initialized. The `hostfxr_initialize...` will block potentially indefinitely. The method will block very early on. All of the operations done by the initialize will only happen once it's unblocked. * `first host context` can fail to initialize the runtime (or anywhere up to that point). If this happens, it's marked as failed and is not considered a `first host context` anymore. This unblocks the potentially waiting `hostfxr_initialize...` calls. In this case the first `hostfxr_initialize...` after the failure will create a new `first host context`. * `first host context` can be closed using `hostfxr_close` before it is used to initialize the CoreCLR runtime. This is similar to the failure above, the host context is marked as "closed/failed" and is not considered `first host context` anymore. This unblocks any waiting `hostfxr_initialize...` calls. * Once the `first host context` successfully initialized the CoreCLR runtime it is permanently marked as "successful" and will remain the `first host context` for the lifetime of the process. Such host context should still be closed once not needed via `hostfxr_close`. #### Invalid usage * It is invalid to initialize a host context via `hostfxr_initialize...` and then never call `hostfxr_close` on it. An initialized but not closed host context is considered abandoned. Abandoned `first host context` will cause infinite blocking of any future `hostfxr_initialize...` calls. #### Important scenarios The above behaviors should make sure that some important scenarios are possible and work reliably. One such scenario is a COM host on multiple threads. The app is not running any .NET Core yet (no CoreCLR loaded). On two threads in parallel COM activation is invoked which leads to two invocations into the `comhost` to active .NET Core objects. The `comhost` will use the `hostfxr_initialize...` and `hostfxr_get_runtime_delegate` APIs on two threads in parallel then. Only one of them can load and initialize the runtime (and also perform full framework resolution and determine the framework versions and assemblies to load). The other has to become a `secondary host context` and try to conform to the first one. The above behavior of `hostfxr_initialize...` blocking until the `first host context` is done initializing the runtime will make sure of the correct behavior in this case. At the same time it gives the native app (`comhost` in this case) the ability to query and modify runtime properties in between the `hostfxr_initialize...` and `hostfxr_get_runtime_delegate` calls on the `first host context`. ### API usage The `hostfxr` exports are defined in the [hostfxr.h](https://github.com/dotnet/runtime/blob/main/src/native/corehost/hostfxr.h) header file. The runtime helper and method signatures for loading managed components are defined in [coreclr_delegates.h](https://github.com/dotnet/runtime/blob/main/src/native/corehost/coreclr_delegates.h) header file. Currently we don't plan to ship these files, but it's possible to take them from the repo and use it. ### Support for older versions Since `hostfxr` and the other hosting components are versioned independently there are several interesting cases of version mismatches: #### muxer/`apphost` versus `hostfxr` For muxer it should almost always match, but `apphost` can be different. That is, it's perfectly valid to use older 2.* `apphost` with a new 3.0 `hostfxr`. The opposite should be rare, but in theory can happen as well. To keep the code simple both muxer and `apphost` will keep using the existing 2.* APIs on `hostfxr` even in situation where both are 3.0 and thus could start using the new APIs. `hostfxr` must be backward compatible and support 2.* APIs. Potentially we could switch just `apphost` to use the new APIs (since it doesn't have the same compatibility burden as the muxer), but it's probably safer to not do that. #### `hostfxr` versus `hostpolicy` It should really only happen that `hostfxr` is equal or newer than `hostpolicy`. The opposite should be very rare. In any case `hostpolicy` should support existing 2.* APIs and thus the rare case will keep working anyway. The interesting case is 3.0 `hostfxr` using 2.* `hostpolicy`. This will be very common, basically any 2.* app running on a machine with 3.0 installed will be in that situation. This case has two sub-cases: * `hostfxr` is invoked using one of the 2.* APIs. In this case the simple solution is to keep using the 2.* `hostpolicy` APIs always. * `hostfxr` is invoked using one of the new 3.0 APIs (like `hostfxr_initialize...`). In this case it's not possible to completely support the new APIs, since they require new functionality from `hostpolicy`. For now the `hostfxr` should simply fail. It is in theory possible to support some kind of emulation mode where for some scenarios the new APIs would work even with old `hostpolicy`, but for simplicity it's better to start with just failing. #### Implementation of existing 2.* APIs in `hostfxr` The existing 2.* APIs in `hostfxr` could switch to internally use the new functionality and in turn use the new 3.0 `hostpolicy` APIs. The tricky bit here is scenario like this: * 3.0 App is started via `apphost` or muxer which as mentioned above will keep on using the 2.* `hostfxr` APIs. This will load CoreCLR into the process. * COM component is activated in the same process. This will go through the new 3.0 `hostfxr` APIs, and to work correctly will require the internal representation of the `first host context`. If the 2.* `hostfxr` APIs would continue to use the old 2.* `hostpolicy` APIs even if `hostpolicy` is new, then the above scenario will be hard to achieve as there will be no `first host context`. `hostpolicy` could somehow "emulate" the `first host context`, but without `hostpolicy` cooperation this would be hard. On the other hand switching to use the new `hostpolicy` APIs even in 2.* `hostfxr` APIs is risky for backward compatibility. This will have to be decided during implementation. ### Samples All samples assume that the native host has found the `hostfxr`, loaded it and got the exports (possibly by using the `nethost`). Samples in general ignore error handling. #### Running app with additional runtime properties ``` C++ hostfxr_initialize_parameters params; params.size = sizeof(params); params.host_path = get_path_to_the_host_exe(); // Path to the current executable params.dotnet_root = get_directory(get_directory(get_directory(hostfxr_path))); // Three levels up from hostfxr typically hostfxr_handle host_context_handle; hostfxr_initialize_for_dotnet_command_line( _argc_, _argv_, // For example, 'app.dll app_argument_1 app_argument_2' &params, &host_context_handle); size_t buffer_used = 0; if (hostfxr_get_runtime_property(host_context_handle, "TEST_PROPERTY", NULL, 0, &buffer_used) == HostApiMissingProperty) { hostfxr_set_runtime_property(host_context_handle, "TEST_PROPERTY", "TRUE"); } hostfxr_run_app(host_context_handle); hostfxr_close(host_context_handle); ``` #### Getting a function pointer to call a managed method ```C++ using load_assembly_and_get_function_pointer_fn = int (STDMETHODCALLTYPE *)( const char_t *assembly_path, const char_t *type_name, const char_t *method_name, const char_t *delegate_type_name, void *reserved, void **delegate); hostfxr_handle host_context_handle; hostfxr_initialize_for_runtime_config(config_path, NULL, &host_context_handle); load_assembly_and_get_function_pointer_fn runtime_delegate = NULL; hostfxr_get_runtime_delegate( host_context_handle, hostfxr_delegate_type::load_assembly_and_get_function_pointer, (void **)&runtime_delegate); using managed_entry_point_fn = int (STDMETHODCALLTYPE *)(void *arg, int argSize); managed_entry_point_fn entry_point = NULL; runtime_delegate(assembly_path, type_name, method_name, NULL, NULL, (void **)&entry_point); ArgStruct arg; entry_point(&arg, sizeof(ArgStruct)); hostfxr_close(host_context_handle); ``` ## Impact on hosting components The exact impact on the `hostfxr`/`hostpolicy` interface needs to be investigated. The assumption is that new APIs will have to be added to `hostpolicy` to implement the proposed functionality. Part if this investigation will also be compatibility behavior. Currently "any" version of `hostfxr` needs to be able to use "any" version of `hostpolicy`. But the proposed functionality will need both new `hostfxr` and new `hostpolicy` to work. It is likely the proposed APIs will fail if the app resolves to a framework with old `hostpolicy` without the necessary new APIs. Part of the investigation will be if it's feasible to use the new `hostpolicy` APIs to implement existing old `hostfxr` APIs. ## Incompatible with trimming Native hosting support on managed side is disabled by default on trimmed apps. Native hosting and trimming are incompatible since the trimmer cannot analyze methods that are called by native hosts. Native hosting support for trimming can be managed through the [feature switch](https://github.com/dotnet/runtime/blob/main/docs/workflow/trimming/feature-switches.md) settings specific to each native host.
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/runtime/dotnet.d.ts
//! Licensed to the .NET Foundation under one or more agreements. //! The .NET Foundation licenses this file to you under the MIT license. //! //! This is generated file, see src/mono/wasm/runtime/rollup.config.js //! This is not considered public API with backward compatibility guarantees. declare interface ManagedPointer { __brandManagedPointer: "ManagedPointer"; } declare interface NativePointer { __brandNativePointer: "NativePointer"; } declare interface VoidPtr extends NativePointer { __brand: "VoidPtr"; } declare interface CharPtr extends NativePointer { __brand: "CharPtr"; } declare interface Int32Ptr extends NativePointer { __brand: "Int32Ptr"; } declare interface EmscriptenModule { HEAP8: Int8Array; HEAP16: Int16Array; HEAP32: Int32Array; HEAPU8: Uint8Array; HEAPU16: Uint16Array; HEAPU32: Uint32Array; HEAPF32: Float32Array; HEAPF64: Float64Array; _malloc(size: number): VoidPtr; _free(ptr: VoidPtr): void; print(message: string): void; printErr(message: string): void; ccall<T>(ident: string, returnType?: string | null, argTypes?: string[], args?: any[], opts?: any): T; cwrap<T extends Function>(ident: string, returnType: string, argTypes?: string[], opts?: any): T; cwrap<T extends Function>(ident: string, ...args: any[]): T; setValue(ptr: VoidPtr, value: number, type: string, noSafe?: number | boolean): void; setValue(ptr: Int32Ptr, value: number, type: string, noSafe?: number | boolean): void; getValue(ptr: number, type: string, noSafe?: number | boolean): number; UTF8ToString(ptr: CharPtr, maxBytesToRead?: number): string; UTF8ArrayToString(u8Array: Uint8Array, idx?: number, maxBytesToRead?: number): string; FS_createPath(parent: string, path: string, canRead?: boolean, canWrite?: boolean): string; FS_createDataFile(parent: string, name: string, data: TypedArray, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; FS_readFile(filename: string, opts: any): any; removeRunDependency(id: string): void; addRunDependency(id: string): void; stackSave(): VoidPtr; stackRestore(stack: VoidPtr): void; stackAlloc(size: number): VoidPtr; ready: Promise<unknown>; preInit?: (() => any)[]; preRun?: (() => any)[]; postRun?: (() => any)[]; onAbort?: { (error: any): void; }; onRuntimeInitialized?: () => any; instantiateWasm: (imports: any, successCallback: Function) => any; } declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; /** * Allocates a block of memory that can safely contain pointers into the managed heap. * The result object has get(index) and set(index, value) methods that can be used to retrieve and store managed pointers. * Once you are done using the root buffer, you must call its release() method. * For small numbers of roots, it is preferable to use the mono_wasm_new_root and mono_wasm_new_roots APIs instead. */ declare function mono_wasm_new_root_buffer(capacity: number, name?: string): WasmRootBuffer; /** * Allocates a WasmRoot pointing to a root provided and controlled by external code. Typicaly on managed stack. * Releasing this root will not de-allocate the root space. You still need to call .release(). */ declare function mono_wasm_new_external_root<T extends MonoObject>(address: VoidPtr | MonoObjectRef): WasmRoot<T>; /** * Allocates temporary storage for a pointer into the managed heap. * Pointers stored here will be visible to the GC, ensuring that the object they point to aren't moved or collected. * If you already have a managed pointer you can pass it as an argument to initialize the temporary storage. * The result object has get() and set(value) methods, along with a .value property. * When you are done using the root you must call its .release() method. */ declare function mono_wasm_new_root<T extends MonoObject>(value?: T | undefined): WasmRoot<T>; /** * Releases 1 or more root or root buffer objects. * Multiple objects may be passed on the argument list. * 'undefined' may be passed as an argument so it is safe to call this method from finally blocks * even if you are not sure all of your roots have been created yet. * @param {... WasmRoot} roots */ declare function mono_wasm_release_roots(...args: WasmRoot<any>[]): void; declare class WasmRootBuffer { private __count; private length; private __offset; private __offset32; private __handle; private __ownsAllocation; constructor(offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string); _throw_index_out_of_range(): void; _check_in_range(index: number): void; get_address(index: number): MonoObjectRef; get_address_32(index: number): number; get(index: number): ManagedPointer; set(index: number, value: ManagedPointer): ManagedPointer; copy_value_from_address(index: number, sourceAddress: MonoObjectRef): void; _unsafe_get(index: number): number; _unsafe_set(index: number, value: ManagedPointer | NativePointer): void; clear(): void; release(): void; toString(): string; } interface WasmRoot<T extends MonoObject> { get_address(): MonoObjectRef; get_address_32(): number; get address(): MonoObjectRef; get(): T; set(value: T): T; get value(): T; set value(value: T); copy_from_address(source: MonoObjectRef): void; copy_to_address(destination: MonoObjectRef): void; copy_from(source: WasmRoot<T>): void; copy_to(destination: WasmRoot<T>): void; valueOf(): T; clear(): void; release(): void; toString(): string; } interface MonoObject extends ManagedPointer { __brandMonoObject: "MonoObject"; } interface MonoString extends MonoObject { __brand: "MonoString"; } interface MonoArray extends MonoObject { __brand: "MonoArray"; } interface MonoObjectRef extends ManagedPointer { __brandMonoObjectRef: "MonoObjectRef"; } declare type MonoConfig = { isError: false; assembly_root: string; assets: AllAssetEntryTypes[]; debug_level?: number; enable_debugging?: number; globalization_mode: GlobalizationMode; diagnostic_tracing?: boolean; remote_sources?: string[]; environment_variables?: { [i: string]: string; }; runtime_options?: string[]; aot_profiler_options?: AOTProfilerOptions; coverage_profiler_options?: CoverageProfilerOptions; ignore_pdb_load_errors?: boolean; wait_for_debugger?: number; }; declare type MonoConfigError = { isError: true; message: string; error: any; }; declare type AllAssetEntryTypes = AssetEntry | AssemblyEntry | SatelliteAssemblyEntry | VfsEntry | IcuData; declare type AssetEntry = { name: string; behavior: AssetBehaviours; virtual_path?: string; culture?: string; load_remote?: boolean; is_optional?: boolean; buffer?: ArrayBuffer; }; interface AssemblyEntry extends AssetEntry { name: "assembly"; } interface SatelliteAssemblyEntry extends AssetEntry { name: "resource"; culture: string; } interface VfsEntry extends AssetEntry { name: "vfs"; virtual_path: string; } interface IcuData extends AssetEntry { name: "icu"; load_remote: boolean; } declare const enum AssetBehaviours { Resource = "resource", Assembly = "assembly", Heap = "heap", ICU = "icu", VFS = "vfs" } declare const enum GlobalizationMode { ICU = "icu", INVARIANT = "invariant", AUTO = "auto" } declare type AOTProfilerOptions = { write_at?: string; send_to?: string; }; declare type CoverageProfilerOptions = { write_at?: string; send_to?: string; }; interface EventPipeSessionOptions { collectRundownEvents?: boolean; providers: string; } declare type DotnetModuleConfig = { disableDotnet6Compatibility?: boolean; config?: MonoConfig | MonoConfigError; configSrc?: string; onConfigLoaded?: (config: MonoConfig) => Promise<void>; onDotnetReady?: () => void; imports?: DotnetModuleConfigImports; exports?: string[]; } & Partial<EmscriptenModule>; declare type DotnetModuleConfigImports = { require?: (name: string) => any; fetch?: (url: string) => Promise<Response>; fs?: { promises?: { readFile?: (path: string) => Promise<string | Buffer>; }; readFileSync?: (path: string, options: any | undefined) => string; }; crypto?: { randomBytes?: (size: number) => Buffer; }; ws?: WebSocket & { Server: any; }; path?: { normalize?: (path: string) => string; dirname?: (path: string) => string; }; url?: any; }; declare type EventPipeSessionID = bigint; interface EventPipeSession { get sessionID(): EventPipeSessionID; start(): void; stop(): void; getTraceBlob(): Blob; } declare const eventLevel: { readonly LogAlways: 0; readonly Critical: 1; readonly Error: 2; readonly Warning: 3; readonly Informational: 4; readonly Verbose: 5; }; declare type EventLevel = typeof eventLevel; declare type UnnamedProviderConfiguration = Partial<{ keyword_mask: string | 0; level: number; args: string; }>; interface ProviderConfiguration extends UnnamedProviderConfiguration { name: string; } declare class SessionOptionsBuilder { private _rundown?; private _providers; constructor(); static get Empty(): SessionOptionsBuilder; static get DefaultProviders(): SessionOptionsBuilder; setRundownEnabled(enabled: boolean): SessionOptionsBuilder; addProvider(provider: ProviderConfiguration): SessionOptionsBuilder; addRuntimeProvider(overrideOptions?: UnnamedProviderConfiguration): SessionOptionsBuilder; addRuntimePrivateProvider(overrideOptions?: UnnamedProviderConfiguration): SessionOptionsBuilder; addSampleProfilerProvider(overrideOptions?: UnnamedProviderConfiguration): SessionOptionsBuilder; build(): EventPipeSessionOptions; } interface Diagnostics { EventLevel: EventLevel; SessionOptionsBuilder: typeof SessionOptionsBuilder; createEventPipeSession(options?: EventPipeSessionOptions): EventPipeSession | null; } declare function mono_wasm_runtime_ready(): void; declare function mono_wasm_setenv(name: string, value: string): void; declare function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoConfigError | undefined): Promise<void>; declare function mono_wasm_load_data_archive(data: Uint8Array, prefix: string): boolean; /** * Loads the mono config file (typically called mono-config.json) asynchroniously * Note: the run dependencies are so emsdk actually awaits it in order. * * @param {string} configFilePath - relative path to the config file * @throws Will throw an error if the config file loading fails */ declare function mono_wasm_load_config(configFilePath: string): Promise<void>; declare function mono_wasm_load_icu_data(offset: VoidPtr): boolean; /** * @deprecated Not GC or thread safe */ declare function conv_string(mono_obj: MonoString): string | null; declare function conv_string_root(root: WasmRoot<MonoString>): string | null; declare function js_string_to_mono_string_root(string: string, result: WasmRoot<MonoString>): void; /** * @deprecated Not GC or thread safe */ declare function js_string_to_mono_string(string: string): MonoString; /** * @deprecated Not GC or thread safe. For blazor use only */ declare function js_to_mono_obj(js_obj: any): MonoObject; declare function js_to_mono_obj_root(js_obj: any, result: WasmRoot<MonoObject>, should_add_in_flight: boolean): void; declare function js_typed_array_to_array_root(js_obj: any, result: WasmRoot<MonoArray>): void; /** * @deprecated Not GC or thread safe */ declare function js_typed_array_to_array(js_obj: any): MonoArray; declare function unbox_mono_obj(mono_obj: MonoObject): any; declare function unbox_mono_obj_root(root: WasmRoot<any>): any; declare function mono_array_to_js_array(mono_array: MonoArray): any[] | null; declare function mono_array_root_to_js_array(arrayRoot: WasmRoot<MonoArray>): any[] | null; declare function mono_bind_static_method(fqn: string, signature?: string): Function; declare function mono_call_assembly_entry_point(assembly: string, args?: any[], signature?: string): number; declare function mono_wasm_load_bytes_into_heap(bytes: Uint8Array): VoidPtr; declare type _MemOffset = number | VoidPtr | NativePointer | ManagedPointer; declare type _NumberOrPointer = number | VoidPtr | NativePointer | ManagedPointer; declare function setB32(offset: _MemOffset, value: number | boolean): void; declare function setU8(offset: _MemOffset, value: number): void; declare function setU16(offset: _MemOffset, value: number): void; declare function setU32(offset: _MemOffset, value: _NumberOrPointer): void; declare function setI8(offset: _MemOffset, value: number): void; declare function setI16(offset: _MemOffset, value: number): void; declare function setI32(offset: _MemOffset, value: number): void; /** * Throws for values which are not 52 bit integer. See Number.isSafeInteger() */ declare function setI52(offset: _MemOffset, value: number): void; /** * Throws for values which are not 52 bit integer or are negative. See Number.isSafeInteger(). */ declare function setU52(offset: _MemOffset, value: number): void; declare function setI64Big(offset: _MemOffset, value: bigint): void; declare function setF32(offset: _MemOffset, value: number): void; declare function setF64(offset: _MemOffset, value: number): void; declare function getB32(offset: _MemOffset): boolean; declare function getU8(offset: _MemOffset): number; declare function getU16(offset: _MemOffset): number; declare function getU32(offset: _MemOffset): number; declare function getI8(offset: _MemOffset): number; declare function getI16(offset: _MemOffset): number; declare function getI32(offset: _MemOffset): number; /** * Throws for Number.MIN_SAFE_INTEGER > value > Number.MAX_SAFE_INTEGER */ declare function getI52(offset: _MemOffset): number; /** * Throws for 0 > value > Number.MAX_SAFE_INTEGER */ declare function getU52(offset: _MemOffset): number; declare function getI64Big(offset: _MemOffset): bigint; declare function getF32(offset: _MemOffset): number; declare function getF64(offset: _MemOffset): number; declare function mono_run_main_and_exit(main_assembly_name: string, args: string[]): Promise<void>; declare function mono_run_main(main_assembly_name: string, args: string[]): Promise<number>; declare const MONO: { mono_wasm_setenv: typeof mono_wasm_setenv; mono_wasm_load_bytes_into_heap: typeof mono_wasm_load_bytes_into_heap; mono_wasm_load_icu_data: typeof mono_wasm_load_icu_data; mono_wasm_runtime_ready: typeof mono_wasm_runtime_ready; mono_wasm_load_data_archive: typeof mono_wasm_load_data_archive; mono_wasm_load_config: typeof mono_wasm_load_config; mono_load_runtime_and_bcl_args: typeof mono_load_runtime_and_bcl_args; mono_wasm_new_root_buffer: typeof mono_wasm_new_root_buffer; mono_wasm_new_root: typeof mono_wasm_new_root; mono_wasm_new_external_root: typeof mono_wasm_new_external_root; mono_wasm_release_roots: typeof mono_wasm_release_roots; mono_run_main: typeof mono_run_main; mono_run_main_and_exit: typeof mono_run_main_and_exit; mono_wasm_add_assembly: (name: string, data: VoidPtr, size: number) => number; mono_wasm_load_runtime: (unused: string, debug_level: number) => void; config: MonoConfig | MonoConfigError; loaded_files: string[]; setB32: typeof setB32; setI8: typeof setI8; setI16: typeof setI16; setI32: typeof setI32; setI52: typeof setI52; setU52: typeof setU52; setI64Big: typeof setI64Big; setU8: typeof setU8; setU16: typeof setU16; setU32: typeof setU32; setF32: typeof setF32; setF64: typeof setF64; getB32: typeof getB32; getI8: typeof getI8; getI16: typeof getI16; getI32: typeof getI32; getI52: typeof getI52; getU52: typeof getU52; getI64Big: typeof getI64Big; getU8: typeof getU8; getU16: typeof getU16; getU32: typeof getU32; getF32: typeof getF32; getF64: typeof getF64; diagnostics: Diagnostics; }; declare type MONOType = typeof MONO; declare const BINDING: { /** * @deprecated Not GC or thread safe */ mono_obj_array_new: (size: number) => MonoArray; /** * @deprecated Not GC or thread safe */ mono_obj_array_set: (array: MonoArray, idx: number, obj: MonoObject) => void; /** * @deprecated Not GC or thread safe */ js_string_to_mono_string: typeof js_string_to_mono_string; /** * @deprecated Not GC or thread safe */ js_typed_array_to_array: typeof js_typed_array_to_array; /** * @deprecated Not GC or thread safe */ mono_array_to_js_array: typeof mono_array_to_js_array; /** * @deprecated Not GC or thread safe */ js_to_mono_obj: typeof js_to_mono_obj; /** * @deprecated Not GC or thread safe */ conv_string: typeof conv_string; /** * @deprecated Not GC or thread safe */ unbox_mono_obj: typeof unbox_mono_obj; /** * @deprecated Renamed to conv_string_root */ conv_string_rooted: typeof conv_string_root; mono_obj_array_new_ref: (size: number, result: MonoObjectRef) => void; mono_obj_array_set_ref: (array: MonoObjectRef, idx: number, obj: MonoObjectRef) => void; js_string_to_mono_string_root: typeof js_string_to_mono_string_root; js_typed_array_to_array_root: typeof js_typed_array_to_array_root; js_to_mono_obj_root: typeof js_to_mono_obj_root; conv_string_root: typeof conv_string_root; unbox_mono_obj_root: typeof unbox_mono_obj_root; mono_array_root_to_js_array: typeof mono_array_root_to_js_array; bind_static_method: typeof mono_bind_static_method; call_assembly_entry_point: typeof mono_call_assembly_entry_point; }; declare type BINDINGType = typeof BINDING; interface DotnetPublicAPI { MONO: typeof MONO; BINDING: typeof BINDING; INTERNAL: any; Module: EmscriptenModule; RuntimeId: number; RuntimeBuildInfo: { ProductVersion: string; Configuration: string; }; } declare function createDotnetRuntime(moduleFactory: DotnetModuleConfig | ((api: DotnetPublicAPI) => DotnetModuleConfig)): Promise<DotnetPublicAPI>; declare type CreateDotnetRuntimeType = typeof createDotnetRuntime; declare global { function getDotnetRuntime(runtimeId: number): DotnetPublicAPI | undefined; } export { BINDINGType, CreateDotnetRuntimeType, DotnetModuleConfig, DotnetPublicAPI, EmscriptenModule, MONOType, MonoArray, MonoObject, MonoString, VoidPtr, createDotnetRuntime as default };
//! Licensed to the .NET Foundation under one or more agreements. //! The .NET Foundation licenses this file to you under the MIT license. //! //! This is generated file, see src/mono/wasm/runtime/rollup.config.js //! This is not considered public API with backward compatibility guarantees. declare interface ManagedPointer { __brandManagedPointer: "ManagedPointer"; } declare interface NativePointer { __brandNativePointer: "NativePointer"; } declare interface VoidPtr extends NativePointer { __brand: "VoidPtr"; } declare interface CharPtr extends NativePointer { __brand: "CharPtr"; } declare interface Int32Ptr extends NativePointer { __brand: "Int32Ptr"; } declare interface EmscriptenModule { HEAP8: Int8Array; HEAP16: Int16Array; HEAP32: Int32Array; HEAPU8: Uint8Array; HEAPU16: Uint16Array; HEAPU32: Uint32Array; HEAPF32: Float32Array; HEAPF64: Float64Array; _malloc(size: number): VoidPtr; _free(ptr: VoidPtr): void; print(message: string): void; printErr(message: string): void; ccall<T>(ident: string, returnType?: string | null, argTypes?: string[], args?: any[], opts?: any): T; cwrap<T extends Function>(ident: string, returnType: string, argTypes?: string[], opts?: any): T; cwrap<T extends Function>(ident: string, ...args: any[]): T; setValue(ptr: VoidPtr, value: number, type: string, noSafe?: number | boolean): void; setValue(ptr: Int32Ptr, value: number, type: string, noSafe?: number | boolean): void; getValue(ptr: number, type: string, noSafe?: number | boolean): number; UTF8ToString(ptr: CharPtr, maxBytesToRead?: number): string; UTF8ArrayToString(u8Array: Uint8Array, idx?: number, maxBytesToRead?: number): string; FS_createPath(parent: string, path: string, canRead?: boolean, canWrite?: boolean): string; FS_createDataFile(parent: string, name: string, data: TypedArray, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; FS_readFile(filename: string, opts: any): any; removeRunDependency(id: string): void; addRunDependency(id: string): void; stackSave(): VoidPtr; stackRestore(stack: VoidPtr): void; stackAlloc(size: number): VoidPtr; ready: Promise<unknown>; preInit?: (() => any)[]; preRun?: (() => any)[]; postRun?: (() => any)[]; onAbort?: { (error: any): void; }; onRuntimeInitialized?: () => any; instantiateWasm: (imports: any, successCallback: Function) => any; } declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; /** * Allocates a block of memory that can safely contain pointers into the managed heap. * The result object has get(index) and set(index, value) methods that can be used to retrieve and store managed pointers. * Once you are done using the root buffer, you must call its release() method. * For small numbers of roots, it is preferable to use the mono_wasm_new_root and mono_wasm_new_roots APIs instead. */ declare function mono_wasm_new_root_buffer(capacity: number, name?: string): WasmRootBuffer; /** * Allocates a WasmRoot pointing to a root provided and controlled by external code. Typicaly on managed stack. * Releasing this root will not de-allocate the root space. You still need to call .release(). */ declare function mono_wasm_new_external_root<T extends MonoObject>(address: VoidPtr | MonoObjectRef): WasmRoot<T>; /** * Allocates temporary storage for a pointer into the managed heap. * Pointers stored here will be visible to the GC, ensuring that the object they point to aren't moved or collected. * If you already have a managed pointer you can pass it as an argument to initialize the temporary storage. * The result object has get() and set(value) methods, along with a .value property. * When you are done using the root you must call its .release() method. */ declare function mono_wasm_new_root<T extends MonoObject>(value?: T | undefined): WasmRoot<T>; /** * Releases 1 or more root or root buffer objects. * Multiple objects may be passed on the argument list. * 'undefined' may be passed as an argument so it is safe to call this method from finally blocks * even if you are not sure all of your roots have been created yet. * @param {... WasmRoot} roots */ declare function mono_wasm_release_roots(...args: WasmRoot<any>[]): void; declare class WasmRootBuffer { private __count; private length; private __offset; private __offset32; private __handle; private __ownsAllocation; constructor(offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string); _throw_index_out_of_range(): void; _check_in_range(index: number): void; get_address(index: number): MonoObjectRef; get_address_32(index: number): number; get(index: number): ManagedPointer; set(index: number, value: ManagedPointer): ManagedPointer; copy_value_from_address(index: number, sourceAddress: MonoObjectRef): void; _unsafe_get(index: number): number; _unsafe_set(index: number, value: ManagedPointer | NativePointer): void; clear(): void; release(): void; toString(): string; } interface WasmRoot<T extends MonoObject> { get_address(): MonoObjectRef; get_address_32(): number; get address(): MonoObjectRef; get(): T; set(value: T): T; get value(): T; set value(value: T); copy_from_address(source: MonoObjectRef): void; copy_to_address(destination: MonoObjectRef): void; copy_from(source: WasmRoot<T>): void; copy_to(destination: WasmRoot<T>): void; valueOf(): T; clear(): void; release(): void; toString(): string; } interface MonoObject extends ManagedPointer { __brandMonoObject: "MonoObject"; } interface MonoString extends MonoObject { __brand: "MonoString"; } interface MonoArray extends MonoObject { __brand: "MonoArray"; } interface MonoObjectRef extends ManagedPointer { __brandMonoObjectRef: "MonoObjectRef"; } declare type MonoConfig = { isError: false; assembly_root: string; assets: AllAssetEntryTypes[]; debug_level?: number; enable_debugging?: number; globalization_mode: GlobalizationMode; diagnostic_tracing?: boolean; remote_sources?: string[]; environment_variables?: { [i: string]: string; }; runtime_options?: string[]; aot_profiler_options?: AOTProfilerOptions; coverage_profiler_options?: CoverageProfilerOptions; ignore_pdb_load_errors?: boolean; wait_for_debugger?: number; }; declare type MonoConfigError = { isError: true; message: string; error: any; }; declare type AllAssetEntryTypes = AssetEntry | AssemblyEntry | SatelliteAssemblyEntry | VfsEntry | IcuData; declare type AssetEntry = { name: string; behavior: AssetBehaviours; virtual_path?: string; culture?: string; load_remote?: boolean; is_optional?: boolean; buffer?: ArrayBuffer; }; interface AssemblyEntry extends AssetEntry { name: "assembly"; } interface SatelliteAssemblyEntry extends AssetEntry { name: "resource"; culture: string; } interface VfsEntry extends AssetEntry { name: "vfs"; virtual_path: string; } interface IcuData extends AssetEntry { name: "icu"; load_remote: boolean; } declare const enum AssetBehaviours { Resource = "resource", Assembly = "assembly", Heap = "heap", ICU = "icu", VFS = "vfs" } declare const enum GlobalizationMode { ICU = "icu", INVARIANT = "invariant", AUTO = "auto" } declare type AOTProfilerOptions = { write_at?: string; send_to?: string; }; declare type CoverageProfilerOptions = { write_at?: string; send_to?: string; }; interface EventPipeSessionOptions { collectRundownEvents?: boolean; providers: string; } declare type DotnetModuleConfig = { disableDotnet6Compatibility?: boolean; config?: MonoConfig | MonoConfigError; configSrc?: string; onConfigLoaded?: (config: MonoConfig) => Promise<void>; onDotnetReady?: () => void; imports?: DotnetModuleConfigImports; exports?: string[]; } & Partial<EmscriptenModule>; declare type DotnetModuleConfigImports = { require?: (name: string) => any; fetch?: (url: string) => Promise<Response>; fs?: { promises?: { readFile?: (path: string) => Promise<string | Buffer>; }; readFileSync?: (path: string, options: any | undefined) => string; }; crypto?: { randomBytes?: (size: number) => Buffer; }; ws?: WebSocket & { Server: any; }; path?: { normalize?: (path: string) => string; dirname?: (path: string) => string; }; url?: any; }; declare type EventPipeSessionID = bigint; interface EventPipeSession { get sessionID(): EventPipeSessionID; start(): void; stop(): void; getTraceBlob(): Blob; } declare const eventLevel: { readonly LogAlways: 0; readonly Critical: 1; readonly Error: 2; readonly Warning: 3; readonly Informational: 4; readonly Verbose: 5; }; declare type EventLevel = typeof eventLevel; declare type UnnamedProviderConfiguration = Partial<{ keyword_mask: string | 0; level: number; args: string; }>; interface ProviderConfiguration extends UnnamedProviderConfiguration { name: string; } declare class SessionOptionsBuilder { private _rundown?; private _providers; constructor(); static get Empty(): SessionOptionsBuilder; static get DefaultProviders(): SessionOptionsBuilder; setRundownEnabled(enabled: boolean): SessionOptionsBuilder; addProvider(provider: ProviderConfiguration): SessionOptionsBuilder; addRuntimeProvider(overrideOptions?: UnnamedProviderConfiguration): SessionOptionsBuilder; addRuntimePrivateProvider(overrideOptions?: UnnamedProviderConfiguration): SessionOptionsBuilder; addSampleProfilerProvider(overrideOptions?: UnnamedProviderConfiguration): SessionOptionsBuilder; build(): EventPipeSessionOptions; } interface Diagnostics { EventLevel: EventLevel; SessionOptionsBuilder: typeof SessionOptionsBuilder; createEventPipeSession(options?: EventPipeSessionOptions): EventPipeSession | null; } declare function mono_wasm_runtime_ready(): void; declare function mono_wasm_setenv(name: string, value: string): void; declare function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoConfigError | undefined): Promise<void>; declare function mono_wasm_load_data_archive(data: Uint8Array, prefix: string): boolean; /** * Loads the mono config file (typically called mono-config.json) asynchroniously * Note: the run dependencies are so emsdk actually awaits it in order. * * @param {string} configFilePath - relative path to the config file * @throws Will throw an error if the config file loading fails */ declare function mono_wasm_load_config(configFilePath: string): Promise<void>; declare function mono_wasm_load_icu_data(offset: VoidPtr): boolean; /** * @deprecated Not GC or thread safe */ declare function conv_string(mono_obj: MonoString): string | null; declare function conv_string_root(root: WasmRoot<MonoString>): string | null; declare function js_string_to_mono_string_root(string: string, result: WasmRoot<MonoString>): void; /** * @deprecated Not GC or thread safe */ declare function js_string_to_mono_string(string: string): MonoString; /** * @deprecated Not GC or thread safe. For blazor use only */ declare function js_to_mono_obj(js_obj: any): MonoObject; declare function js_to_mono_obj_root(js_obj: any, result: WasmRoot<MonoObject>, should_add_in_flight: boolean): void; declare function js_typed_array_to_array_root(js_obj: any, result: WasmRoot<MonoArray>): void; /** * @deprecated Not GC or thread safe */ declare function js_typed_array_to_array(js_obj: any): MonoArray; declare function unbox_mono_obj(mono_obj: MonoObject): any; declare function unbox_mono_obj_root(root: WasmRoot<any>): any; declare function mono_array_to_js_array(mono_array: MonoArray): any[] | null; declare function mono_array_root_to_js_array(arrayRoot: WasmRoot<MonoArray>): any[] | null; declare function mono_bind_static_method(fqn: string, signature?: string): Function; declare function mono_call_assembly_entry_point(assembly: string, args?: any[], signature?: string): number; declare function mono_wasm_load_bytes_into_heap(bytes: Uint8Array): VoidPtr; declare type _MemOffset = number | VoidPtr | NativePointer | ManagedPointer; declare type _NumberOrPointer = number | VoidPtr | NativePointer | ManagedPointer; declare function setB32(offset: _MemOffset, value: number | boolean): void; declare function setU8(offset: _MemOffset, value: number): void; declare function setU16(offset: _MemOffset, value: number): void; declare function setU32(offset: _MemOffset, value: _NumberOrPointer): void; declare function setI8(offset: _MemOffset, value: number): void; declare function setI16(offset: _MemOffset, value: number): void; declare function setI32(offset: _MemOffset, value: number): void; /** * Throws for values which are not 52 bit integer. See Number.isSafeInteger() */ declare function setI52(offset: _MemOffset, value: number): void; /** * Throws for values which are not 52 bit integer or are negative. See Number.isSafeInteger(). */ declare function setU52(offset: _MemOffset, value: number): void; declare function setI64Big(offset: _MemOffset, value: bigint): void; declare function setF32(offset: _MemOffset, value: number): void; declare function setF64(offset: _MemOffset, value: number): void; declare function getB32(offset: _MemOffset): boolean; declare function getU8(offset: _MemOffset): number; declare function getU16(offset: _MemOffset): number; declare function getU32(offset: _MemOffset): number; declare function getI8(offset: _MemOffset): number; declare function getI16(offset: _MemOffset): number; declare function getI32(offset: _MemOffset): number; /** * Throws for Number.MIN_SAFE_INTEGER > value > Number.MAX_SAFE_INTEGER */ declare function getI52(offset: _MemOffset): number; /** * Throws for 0 > value > Number.MAX_SAFE_INTEGER */ declare function getU52(offset: _MemOffset): number; declare function getI64Big(offset: _MemOffset): bigint; declare function getF32(offset: _MemOffset): number; declare function getF64(offset: _MemOffset): number; declare function mono_run_main_and_exit(main_assembly_name: string, args: string[]): Promise<void>; declare function mono_run_main(main_assembly_name: string, args: string[]): Promise<number>; declare const MONO: { mono_wasm_setenv: typeof mono_wasm_setenv; mono_wasm_load_bytes_into_heap: typeof mono_wasm_load_bytes_into_heap; mono_wasm_load_icu_data: typeof mono_wasm_load_icu_data; mono_wasm_runtime_ready: typeof mono_wasm_runtime_ready; mono_wasm_load_data_archive: typeof mono_wasm_load_data_archive; mono_wasm_load_config: typeof mono_wasm_load_config; mono_load_runtime_and_bcl_args: typeof mono_load_runtime_and_bcl_args; mono_wasm_new_root_buffer: typeof mono_wasm_new_root_buffer; mono_wasm_new_root: typeof mono_wasm_new_root; mono_wasm_new_external_root: typeof mono_wasm_new_external_root; mono_wasm_release_roots: typeof mono_wasm_release_roots; mono_run_main: typeof mono_run_main; mono_run_main_and_exit: typeof mono_run_main_and_exit; mono_wasm_add_assembly: (name: string, data: VoidPtr, size: number) => number; mono_wasm_load_runtime: (unused: string, debug_level: number) => void; config: MonoConfig | MonoConfigError; loaded_files: string[]; setB32: typeof setB32; setI8: typeof setI8; setI16: typeof setI16; setI32: typeof setI32; setI52: typeof setI52; setU52: typeof setU52; setI64Big: typeof setI64Big; setU8: typeof setU8; setU16: typeof setU16; setU32: typeof setU32; setF32: typeof setF32; setF64: typeof setF64; getB32: typeof getB32; getI8: typeof getI8; getI16: typeof getI16; getI32: typeof getI32; getI52: typeof getI52; getU52: typeof getU52; getI64Big: typeof getI64Big; getU8: typeof getU8; getU16: typeof getU16; getU32: typeof getU32; getF32: typeof getF32; getF64: typeof getF64; diagnostics: Diagnostics; }; declare type MONOType = typeof MONO; declare const BINDING: { /** * @deprecated Not GC or thread safe */ mono_obj_array_new: (size: number) => MonoArray; /** * @deprecated Not GC or thread safe */ mono_obj_array_set: (array: MonoArray, idx: number, obj: MonoObject) => void; /** * @deprecated Not GC or thread safe */ js_string_to_mono_string: typeof js_string_to_mono_string; /** * @deprecated Not GC or thread safe */ js_typed_array_to_array: typeof js_typed_array_to_array; /** * @deprecated Not GC or thread safe */ mono_array_to_js_array: typeof mono_array_to_js_array; /** * @deprecated Not GC or thread safe */ js_to_mono_obj: typeof js_to_mono_obj; /** * @deprecated Not GC or thread safe */ conv_string: typeof conv_string; /** * @deprecated Not GC or thread safe */ unbox_mono_obj: typeof unbox_mono_obj; /** * @deprecated Renamed to conv_string_root */ conv_string_rooted: typeof conv_string_root; mono_obj_array_new_ref: (size: number, result: MonoObjectRef) => void; mono_obj_array_set_ref: (array: MonoObjectRef, idx: number, obj: MonoObjectRef) => void; js_string_to_mono_string_root: typeof js_string_to_mono_string_root; js_typed_array_to_array_root: typeof js_typed_array_to_array_root; js_to_mono_obj_root: typeof js_to_mono_obj_root; conv_string_root: typeof conv_string_root; unbox_mono_obj_root: typeof unbox_mono_obj_root; mono_array_root_to_js_array: typeof mono_array_root_to_js_array; bind_static_method: typeof mono_bind_static_method; call_assembly_entry_point: typeof mono_call_assembly_entry_point; }; declare type BINDINGType = typeof BINDING; interface DotnetPublicAPI { MONO: typeof MONO; BINDING: typeof BINDING; INTERNAL: any; Module: EmscriptenModule; RuntimeId: number; RuntimeBuildInfo: { ProductVersion: string; Configuration: string; }; } declare function createDotnetRuntime(moduleFactory: DotnetModuleConfig | ((api: DotnetPublicAPI) => DotnetModuleConfig)): Promise<DotnetPublicAPI>; declare type CreateDotnetRuntimeType = typeof createDotnetRuntime; declare global { function getDotnetRuntime(runtimeId: number): DotnetPublicAPI | undefined; } export { BINDINGType, CreateDotnetRuntimeType, DotnetModuleConfig, DotnetPublicAPI, EmscriptenModule, MONOType, MonoArray, MonoObject, MonoString, VoidPtr, createDotnetRuntime as default };
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/sample/wasm/browser-webpack/README.md
## Sample for packaging dotnet.js via WebPack ``` dotnet build /p:TargetOS=Browser /p:TargetArchitecture=wasm /p:Configuration=Debug /t:RunSample ```
## Sample for packaging dotnet.js via WebPack ``` dotnet build /p:TargetOS=Browser /p:TargetArchitecture=wasm /p:Configuration=Debug /t:RunSample ```
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./docs/design/coreclr/profiling/davbr-blog-archive/DoStackSnapshot - Exception Filters.md
*This blog post originally appeared on David Broman's blog on 10/10/2005* Believe it or not, my last (rather large) post on stack walking actually left out several miscellaneous details about using DoStackSnapshot. I'll be posting those details separately. We'll start off with some light reading on exception filters. No deadlocks this time, I promise. For those of you diehard C# fans, you might be unaware of the existence of exception filters in managed code. While VB.NET makes them explicitly available to the programmer, C# does not. Filters are important to understand when you call DoStackSnapshot, as your results might look a little weird if you don't know how to interpret them. First, a little background. For the full deal, check out the MSDN Library topic on VB.NET's [try/catch/finally statements](http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmTryCatchFinally.asp). But here's an appetizer. In VB.NET you can do this: ``` Function Negative() As Boolean Return False End Function Function Positive() As Boolean Return True End Function Sub Thrower Throw New Exception End Sub Sub Main() Try Thrower() Catch ex As Exception When Negative() MsgBox("Negative") Catch ex As Exception When Positive() MsgBox("Positive") End Try End Sub ``` The filters are the things that come after "When". We all know that, when an exception is thrown, its type must match the type specified in a Catch clause in order for that Catch clause to be executed. "When" is a way to further restrict whether a Catch clause will be executed. Now, not only must the exception's type match, but also the When clause must evaluate to True for that Catch clause to be chosen. In the example above, when we run, we'll skip the first Catch clause (because its filter returned False), and execute the second, thus showing a message box with "Positive" in it. The thing you need to realize about DoStackSnapshot's behavior (indeed, CLR in general) is that the execution of a When clause is really a separate function call. In the above example, imagine we take a stack snapshot while inside Positive(). Our managed-only stack trace, as reported by DoStackSnapshot, would then look like this (stack grows up): Positive\ Main\ Thrower\ Main It's that highlighted Main that seems odd at first. While the exception is thrown inside Thrower(), the CLR needs to execute the filter clauses to figure out which Catch wins. These filter executions are actually _function calls_. Since filter clauses don't have their own names, we just use the name of the function containing the filter clause for stack reporting purposes. Thus, the highlighted Main above is the execution of a filter clause located inside Main (in this case, "When Positive()"). When each filter clause completes, we "return" back to Thrower() to continue our search for the filter that returns True. Since this is how the call stack is built up, that's what DoStackSnapshot will report.
*This blog post originally appeared on David Broman's blog on 10/10/2005* Believe it or not, my last (rather large) post on stack walking actually left out several miscellaneous details about using DoStackSnapshot. I'll be posting those details separately. We'll start off with some light reading on exception filters. No deadlocks this time, I promise. For those of you diehard C# fans, you might be unaware of the existence of exception filters in managed code. While VB.NET makes them explicitly available to the programmer, C# does not. Filters are important to understand when you call DoStackSnapshot, as your results might look a little weird if you don't know how to interpret them. First, a little background. For the full deal, check out the MSDN Library topic on VB.NET's [try/catch/finally statements](http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmTryCatchFinally.asp). But here's an appetizer. In VB.NET you can do this: ``` Function Negative() As Boolean Return False End Function Function Positive() As Boolean Return True End Function Sub Thrower Throw New Exception End Sub Sub Main() Try Thrower() Catch ex As Exception When Negative() MsgBox("Negative") Catch ex As Exception When Positive() MsgBox("Positive") End Try End Sub ``` The filters are the things that come after "When". We all know that, when an exception is thrown, its type must match the type specified in a Catch clause in order for that Catch clause to be executed. "When" is a way to further restrict whether a Catch clause will be executed. Now, not only must the exception's type match, but also the When clause must evaluate to True for that Catch clause to be chosen. In the example above, when we run, we'll skip the first Catch clause (because its filter returned False), and execute the second, thus showing a message box with "Positive" in it. The thing you need to realize about DoStackSnapshot's behavior (indeed, CLR in general) is that the execution of a When clause is really a separate function call. In the above example, imagine we take a stack snapshot while inside Positive(). Our managed-only stack trace, as reported by DoStackSnapshot, would then look like this (stack grows up): Positive\ Main\ Thrower\ Main It's that highlighted Main that seems odd at first. While the exception is thrown inside Thrower(), the CLR needs to execute the filter clauses to figure out which Catch wins. These filter executions are actually _function calls_. Since filter clauses don't have their own names, we just use the name of the function containing the filter clause for stack reporting purposes. Thus, the highlighted Main above is the execution of a filter clause located inside Main (in this case, "When Positive()"). When each filter clause completes, we "return" back to Thrower() to continue our search for the filter that returns True. Since this is how the call stack is built up, that's what DoStackSnapshot will report.
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Diagnostics.StackTrace/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/wasm/runtime/gc-handles.ts
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. import corebindings from "./corebindings"; import { GCHandle, JSHandle, JSHandleDisposed, JSHandleNull, MonoObjectRef } from "./types"; import { setI32_unchecked } from "./memory"; import { create_weak_ref } from "./weak-ref"; export const _use_finalization_registry = typeof globalThis.FinalizationRegistry === "function"; export let _js_owned_object_registry: FinalizationRegistry<any>; // this is array, not map. We maintain list of gaps in _js_handle_free_list so that it could be as compact as possible const _cs_owned_objects_by_js_handle: any[] = []; const _js_handle_free_list: JSHandle[] = []; let _next_js_handle = 1; const _js_owned_object_table = new Map(); // NOTE: FinalizationRegistry and WeakRef are missing on Safari below 14.1 if (_use_finalization_registry) { _js_owned_object_registry = new globalThis.FinalizationRegistry(_js_owned_object_finalized); } export const js_owned_gc_handle_symbol = Symbol.for("wasm js_owned_gc_handle"); export const cs_owned_js_handle_symbol = Symbol.for("wasm cs_owned_js_handle"); export function get_js_owned_object_by_gc_handle_ref(gc_handle: GCHandle, result: MonoObjectRef): void { if (!gc_handle) { setI32_unchecked(result, 0); return; } // this is always strong gc_handle corebindings._get_js_owned_object_by_gc_handle_ref(gc_handle, result); } export function mono_wasm_get_jsobj_from_js_handle(js_handle: JSHandle): any { if (js_handle !== JSHandleNull && js_handle !== JSHandleDisposed) return _cs_owned_objects_by_js_handle[<any>js_handle]; return null; } // when should_add_in_flight === true, the JSObject would be temporarily hold by Normal gc_handle, so that it would not get collected during transition to the managed stack. // its InFlight gc_handle would be freed when the instance arrives to managed side via Interop.Runtime.ReleaseInFlight export function get_cs_owned_object_by_js_handle_ref(js_handle: JSHandle, should_add_in_flight: boolean, result: MonoObjectRef): void { if (js_handle === JSHandleNull || js_handle === JSHandleDisposed) { setI32_unchecked(result, 0); return; } corebindings._get_cs_owned_object_by_js_handle_ref(js_handle, should_add_in_flight ? 1 : 0, result); } export function get_js_obj(js_handle: JSHandle): any { if (js_handle !== JSHandleNull && js_handle !== JSHandleDisposed) return mono_wasm_get_jsobj_from_js_handle(js_handle); return null; } export function _js_owned_object_finalized(gc_handle: GCHandle): void { // The JS object associated with this gc_handle has been collected by the JS GC. // As such, it's not possible for this gc_handle to be invoked by JS anymore, so // we can release the tracking weakref (it's null now, by definition), // and tell the C# side to stop holding a reference to the managed object. // "The FinalizationRegistry callback is called potentially multiple times" if (_js_owned_object_table.delete(gc_handle)) { corebindings._release_js_owned_object_by_gc_handle(gc_handle); } } export function _lookup_js_owned_object(gc_handle: GCHandle): any { if (!gc_handle) return null; const wr = _js_owned_object_table.get(gc_handle); if (wr) { return wr.deref(); // TODO: could this be null before _js_owned_object_finalized was called ? // TODO: are there race condition consequences ? } return null; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function _register_js_owned_object(gc_handle: GCHandle, js_obj: any): void { const wr = create_weak_ref(js_obj); _js_owned_object_table.set(gc_handle, wr); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function mono_wasm_get_js_handle(js_obj: any): JSHandle { if (js_obj[cs_owned_js_handle_symbol]) { return js_obj[cs_owned_js_handle_symbol]; } const js_handle = _js_handle_free_list.length ? _js_handle_free_list.pop() : _next_js_handle++; // note _cs_owned_objects_by_js_handle is list, not Map. That's why we maintain _js_handle_free_list. _cs_owned_objects_by_js_handle[<number>js_handle!] = js_obj; js_obj[cs_owned_js_handle_symbol] = js_handle; return js_handle as JSHandle; } export function mono_wasm_release_cs_owned_object(js_handle: JSHandle): void { const obj = _cs_owned_objects_by_js_handle[<any>js_handle]; if (typeof obj !== "undefined" && obj !== null) { // if this is the global object then do not // unregister it. if (globalThis === obj) return; if (typeof obj[cs_owned_js_handle_symbol] !== "undefined") { obj[cs_owned_js_handle_symbol] = undefined; } _cs_owned_objects_by_js_handle[<any>js_handle] = undefined; _js_handle_free_list.push(js_handle); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. import corebindings from "./corebindings"; import { GCHandle, JSHandle, JSHandleDisposed, JSHandleNull, MonoObjectRef } from "./types"; import { setI32_unchecked } from "./memory"; import { create_weak_ref } from "./weak-ref"; export const _use_finalization_registry = typeof globalThis.FinalizationRegistry === "function"; export let _js_owned_object_registry: FinalizationRegistry<any>; // this is array, not map. We maintain list of gaps in _js_handle_free_list so that it could be as compact as possible const _cs_owned_objects_by_js_handle: any[] = []; const _js_handle_free_list: JSHandle[] = []; let _next_js_handle = 1; const _js_owned_object_table = new Map(); // NOTE: FinalizationRegistry and WeakRef are missing on Safari below 14.1 if (_use_finalization_registry) { _js_owned_object_registry = new globalThis.FinalizationRegistry(_js_owned_object_finalized); } export const js_owned_gc_handle_symbol = Symbol.for("wasm js_owned_gc_handle"); export const cs_owned_js_handle_symbol = Symbol.for("wasm cs_owned_js_handle"); export function get_js_owned_object_by_gc_handle_ref(gc_handle: GCHandle, result: MonoObjectRef): void { if (!gc_handle) { setI32_unchecked(result, 0); return; } // this is always strong gc_handle corebindings._get_js_owned_object_by_gc_handle_ref(gc_handle, result); } export function mono_wasm_get_jsobj_from_js_handle(js_handle: JSHandle): any { if (js_handle !== JSHandleNull && js_handle !== JSHandleDisposed) return _cs_owned_objects_by_js_handle[<any>js_handle]; return null; } // when should_add_in_flight === true, the JSObject would be temporarily hold by Normal gc_handle, so that it would not get collected during transition to the managed stack. // its InFlight gc_handle would be freed when the instance arrives to managed side via Interop.Runtime.ReleaseInFlight export function get_cs_owned_object_by_js_handle_ref(js_handle: JSHandle, should_add_in_flight: boolean, result: MonoObjectRef): void { if (js_handle === JSHandleNull || js_handle === JSHandleDisposed) { setI32_unchecked(result, 0); return; } corebindings._get_cs_owned_object_by_js_handle_ref(js_handle, should_add_in_flight ? 1 : 0, result); } export function get_js_obj(js_handle: JSHandle): any { if (js_handle !== JSHandleNull && js_handle !== JSHandleDisposed) return mono_wasm_get_jsobj_from_js_handle(js_handle); return null; } export function _js_owned_object_finalized(gc_handle: GCHandle): void { // The JS object associated with this gc_handle has been collected by the JS GC. // As such, it's not possible for this gc_handle to be invoked by JS anymore, so // we can release the tracking weakref (it's null now, by definition), // and tell the C# side to stop holding a reference to the managed object. // "The FinalizationRegistry callback is called potentially multiple times" if (_js_owned_object_table.delete(gc_handle)) { corebindings._release_js_owned_object_by_gc_handle(gc_handle); } } export function _lookup_js_owned_object(gc_handle: GCHandle): any { if (!gc_handle) return null; const wr = _js_owned_object_table.get(gc_handle); if (wr) { return wr.deref(); // TODO: could this be null before _js_owned_object_finalized was called ? // TODO: are there race condition consequences ? } return null; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function _register_js_owned_object(gc_handle: GCHandle, js_obj: any): void { const wr = create_weak_ref(js_obj); _js_owned_object_table.set(gc_handle, wr); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function mono_wasm_get_js_handle(js_obj: any): JSHandle { if (js_obj[cs_owned_js_handle_symbol]) { return js_obj[cs_owned_js_handle_symbol]; } const js_handle = _js_handle_free_list.length ? _js_handle_free_list.pop() : _next_js_handle++; // note _cs_owned_objects_by_js_handle is list, not Map. That's why we maintain _js_handle_free_list. _cs_owned_objects_by_js_handle[<number>js_handle!] = js_obj; js_obj[cs_owned_js_handle_symbol] = js_handle; return js_handle as JSHandle; } export function mono_wasm_release_cs_owned_object(js_handle: JSHandle): void { const obj = _cs_owned_objects_by_js_handle[<any>js_handle]; if (typeof obj !== "undefined" && obj !== null) { // if this is the global object then do not // unregister it. if (globalThis === obj) return; if (typeof obj[cs_owned_js_handle_symbol] !== "undefined") { obj[cs_owned_js_handle_symbol] = undefined; } _cs_owned_objects_by_js_handle[<any>js_handle] = undefined; _js_handle_free_list.push(js_handle); } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/HardwareIntrinsics/General/Vector256/GreaterThanOrEqualAny.Int64.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GreaterThanOrEqualAnyInt64() { var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int64> _fld1; public Vector256<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64 testClass) { var result = Vector256.GreaterThanOrEqualAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.GreaterThanOrEqualAny( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAny), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAny), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int64)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.GreaterThanOrEqualAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Vector256.GreaterThanOrEqualAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64(); var result = Vector256.GreaterThanOrEqualAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.GreaterThanOrEqualAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.GreaterThanOrEqualAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] >= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.GreaterThanOrEqualAny)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GreaterThanOrEqualAnyInt64() { var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int64> _fld1; public Vector256<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64 testClass) { var result = Vector256.GreaterThanOrEqualAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.GreaterThanOrEqualAny( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAny), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanOrEqualAny), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int64)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.GreaterThanOrEqualAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Vector256.GreaterThanOrEqualAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAnyInt64(); var result = Vector256.GreaterThanOrEqualAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.GreaterThanOrEqualAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.GreaterThanOrEqualAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] >= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.GreaterThanOrEqualAny)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/opt/Devirtualization/readonlystatic.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="readonlystatic.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="readonlystatic.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ConvertToInt32RoundToEvenScalar.Vector64.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ConvertToInt32RoundToEvenScalar_Vector64_Single() { var test = new SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single testClass) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToInt32RoundToEvenScalar), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToInt32RoundToEvenScalar), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single(); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ConvertToInt32RoundToEven(firstOp[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ConvertToInt32RoundToEvenScalar)}<Int32>(Vector64<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ConvertToInt32RoundToEvenScalar_Vector64_Single() { var test = new SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single testClass) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToInt32RoundToEvenScalar), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToInt32RoundToEvenScalar), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single(); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ConvertToInt32RoundToEvenScalar_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToInt32RoundToEvenScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToInt32RoundToEvenScalar( AdvSimd.LoadVector64((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ConvertToInt32RoundToEven(firstOp[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ConvertToInt32RoundToEvenScalar)}<Int32>(Vector64<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Collections.Specialized/tests/NameValueCollection/NameValueCollection.CopyToTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Collections.Specialized.Tests { public class NameValueCollectionCopyToTests { [Theory] [InlineData(0, 0)] [InlineData(0, 1)] [InlineData(5, 0)] [InlineData(5, 1)] public void CopyTo(int count, int index) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); string[] dest = new string[count + index + 5]; nameValueCollection.CopyTo(dest, index); for (int i = 0; i < index; i++) { Assert.Null(dest[i]); } for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } for (int i = index + count; i < dest.Length; i++) { Assert.Null(dest[i]); } nameValueCollection.CopyTo(dest, index); for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } } [Fact] public void CopyTo_MultipleValues_SameName() { NameValueCollection nameValueCollection = new NameValueCollection(); string name = "name"; nameValueCollection.Add(name, "value1"); nameValueCollection.Add(name, "value2"); nameValueCollection.Add(name, "value3"); string[] dest = new string[1]; nameValueCollection.CopyTo(dest, 0); Assert.Equal(nameValueCollection[0], dest[0]); } [Theory] [InlineData(0)] [InlineData(5)] public void CopyTo_Invalid(int count) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); AssertExtensions.Throws<ArgumentNullException>("dest", () => nameValueCollection.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentException>("dest", null, () => nameValueCollection.CopyTo(new string[count, count], 0)); // in .NET Framework when passing multidimensional arrays Exception.ParamName is null. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => nameValueCollection.CopyTo(new string[count], -1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], 1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count + 1)); if (count > 0) { AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count)); Assert.Throws<InvalidCastException>(() => nameValueCollection.CopyTo(new DictionaryEntry[count], 0)); } else { // InvalidCastException should not throw for an empty NameValueCollection nameValueCollection.CopyTo(new DictionaryEntry[count], 0); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Collections.Specialized.Tests { public class NameValueCollectionCopyToTests { [Theory] [InlineData(0, 0)] [InlineData(0, 1)] [InlineData(5, 0)] [InlineData(5, 1)] public void CopyTo(int count, int index) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); string[] dest = new string[count + index + 5]; nameValueCollection.CopyTo(dest, index); for (int i = 0; i < index; i++) { Assert.Null(dest[i]); } for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } for (int i = index + count; i < dest.Length; i++) { Assert.Null(dest[i]); } nameValueCollection.CopyTo(dest, index); for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } } [Fact] public void CopyTo_MultipleValues_SameName() { NameValueCollection nameValueCollection = new NameValueCollection(); string name = "name"; nameValueCollection.Add(name, "value1"); nameValueCollection.Add(name, "value2"); nameValueCollection.Add(name, "value3"); string[] dest = new string[1]; nameValueCollection.CopyTo(dest, 0); Assert.Equal(nameValueCollection[0], dest[0]); } [Theory] [InlineData(0)] [InlineData(5)] public void CopyTo_Invalid(int count) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); AssertExtensions.Throws<ArgumentNullException>("dest", () => nameValueCollection.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentException>("dest", null, () => nameValueCollection.CopyTo(new string[count, count], 0)); // in .NET Framework when passing multidimensional arrays Exception.ParamName is null. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => nameValueCollection.CopyTo(new string[count], -1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], 1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count + 1)); if (count > 0) { AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count)); Assert.Throws<InvalidCastException>(() => nameValueCollection.CopyTo(new DictionaryEntry[count], 0)); } else { // InvalidCastException should not throw for an empty NameValueCollection nameValueCollection.CopyTo(new DictionaryEntry[count], 0); } } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheKeyEqualityComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Diagnostics; namespace System.Runtime.Caching { internal sealed class MemoryCacheEqualityComparer : IEqualityComparer { bool IEqualityComparer.Equals(object x, object y) { Debug.Assert(x != null && x is MemoryCacheKey); Debug.Assert(y != null && y is MemoryCacheKey); MemoryCacheKey a, b; a = (MemoryCacheKey)x; b = (MemoryCacheKey)y; return string.Equals(a.Key, b.Key, StringComparison.Ordinal); } int IEqualityComparer.GetHashCode(object obj) { MemoryCacheKey cacheKey = (MemoryCacheKey)obj; return cacheKey.Hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Diagnostics; namespace System.Runtime.Caching { internal sealed class MemoryCacheEqualityComparer : IEqualityComparer { bool IEqualityComparer.Equals(object x, object y) { Debug.Assert(x != null && x is MemoryCacheKey); Debug.Assert(y != null && y is MemoryCacheKey); MemoryCacheKey a, b; a = (MemoryCacheKey)x; b = (MemoryCacheKey)y; return string.Equals(a.Key, b.Key, StringComparison.Ordinal); } int IEqualityComparer.GetHashCode(object obj) { MemoryCacheKey cacheKey = (MemoryCacheKey)obj; return cacheKey.Hash; } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/Methodical/explicit/funcptr/expl_funcptr_gc_il_d.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="expl_funcptr_gc.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="expl_funcptr_gc.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/CompareLessThan.Vector128.SByte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void CompareLessThan_Vector128_SByte() { var test = new SimpleBinaryOpTest__CompareLessThan_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareLessThan_Vector128_SByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareLessThan_Vector128_SByte testClass) { var result = AdvSimd.CompareLessThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareLessThan_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareLessThan_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__CompareLessThan_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.CompareLessThan( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.CompareLessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.CompareLessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.CompareLessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareLessThan_Vector128_SByte(); var result = AdvSimd.CompareLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareLessThan_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.CompareLessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.CompareLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.CompareLessThan(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.CompareLessThan)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void CompareLessThan_Vector128_SByte() { var test = new SimpleBinaryOpTest__CompareLessThan_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareLessThan_Vector128_SByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareLessThan_Vector128_SByte testClass) { var result = AdvSimd.CompareLessThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareLessThan_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareLessThan_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__CompareLessThan_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.CompareLessThan( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.CompareLessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.CompareLessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.CompareLessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareLessThan_Vector128_SByte(); var result = AdvSimd.CompareLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareLessThan_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.CompareLessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.CompareLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.CompareLessThan( AdvSimd.LoadVector128((SByte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.CompareLessThan(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.CompareLessThan)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/GC/Regressions/v2.0-rtm/544701/544701.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/ResultFlags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.Pipelines { [Flags] internal enum ResultFlags : byte { None = 0x0, Canceled = 0x1, Completed = 0x2 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.Pipelines { [Flags] internal enum ResultFlags : byte { None = 0x0, Canceled = 0x1, Completed = 0x2 } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest1420/Generated1420.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated1420.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated1420.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.IO.Ports/tests/SerialPort/ReadChar_Generic.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO.PortsTests; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Ports.Tests { public class ReadChar_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the read method and the testcase fails. private const double maxPercentageDifference = .15; //The number of random characters to receive private const int numRndChar = 8; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.ReadChar()); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); var t = new Task(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine( "Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); //Call WriteToCom1 asynchronously this will write to com1 some time before the following call //to a read method times out t.Start(); try { com1.ReadChar(); } catch (TimeoutException) { } TCSupport.WaitForTaskCompletion(t); //Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] xmitBuffer = new byte[1]; int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.Write(xmitBuffer, 0, xmitBuffer.Length); } } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndChar - 2); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndChar - 1)); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndChar]; char[] expectedChars = new char[numRndChar]; char[] actualChars = new char[numRndChar + 1]; int actualCharIndex = 0; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1); while (true) { int charRead; try { charRead = com1.ReadChar(); } catch (TimeoutException) { break; } actualChars[actualCharIndex] = (char)charRead; actualCharIndex++; } Assert.Equal(expectedChars, actualChars.Take(expectedChars.Length).ToArray()); if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; Assert.Throws<TimeoutException>(() => com.ReadChar()); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); Assert.Throws<TimeoutException>(() => com.ReadChar()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.ReadChar()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] byteBuffer = new byte[numRndChar]; char[] charBuffer = new char[numRndChar]; int expectedChar; //Genrate random characters without an parity error for (int i = 0; i < byteBuffer.Length; i++) { int randChar = rndGen.Next(0, 128); byteBuffer[i] = (byte)randChar; charBuffer[i] = (char)randChar; } if (-1 == parityReplace) { //If parityReplace is -1 and we should just use the default value expectedChar = com1.ParityReplace; } else if ('\0' == parityReplace) { //If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedChar = charBuffer[parityErrorIndex]; } else { //Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedChar = parityReplace; } //Create an parity error by setting the highest order bit to true byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); charBuffer[parityErrorIndex] = (char)expectedChar; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Open(); com2.Open(); VerifyRead(com1, com2, byteBuffer, charBuffer); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] charRcvBuffer = new char[expectedChars.Length]; int rcvBufferSize = 0; int i; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); i = 0; while (true) { int readInt; try { readInt = com1.ReadChar(); } catch (TimeoutException) { break; } //While their are more characters to be read if (expectedChars.Length <= i) { //If we have read in more characters then we expecte Fail("ERROR!!!: We have received more characters then were sent"); } charRcvBuffer[i] = (char)readInt; rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1); if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); } if (readInt != expectedChars[i]) { //If the character read is not the expected character Fail("ERROR!!!: Expected to read {0} actual read char {1}", expectedChars[i], (char)readInt); } i++; } Assert.Equal(expectedChars.Length, i); } #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.Diagnostics; using System.IO.PortsTests; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Ports.Tests { public class ReadChar_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the read method and the testcase fails. private const double maxPercentageDifference = .15; //The number of random characters to receive private const int numRndChar = 8; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.ReadChar()); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); var t = new Task(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine( "Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); //Call WriteToCom1 asynchronously this will write to com1 some time before the following call //to a read method times out t.Start(); try { com1.ReadChar(); } catch (TimeoutException) { } TCSupport.WaitForTaskCompletion(t); //Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] xmitBuffer = new byte[1]; int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.Write(xmitBuffer, 0, xmitBuffer.Length); } } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndChar - 2); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndChar - 1)); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndChar]; char[] expectedChars = new char[numRndChar]; char[] actualChars = new char[numRndChar + 1]; int actualCharIndex = 0; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1); while (true) { int charRead; try { charRead = com1.ReadChar(); } catch (TimeoutException) { break; } actualChars[actualCharIndex] = (char)charRead; actualCharIndex++; } Assert.Equal(expectedChars, actualChars.Take(expectedChars.Length).ToArray()); if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; Assert.Throws<TimeoutException>(() => com.ReadChar()); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); Assert.Throws<TimeoutException>(() => com.ReadChar()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.ReadChar()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] byteBuffer = new byte[numRndChar]; char[] charBuffer = new char[numRndChar]; int expectedChar; //Genrate random characters without an parity error for (int i = 0; i < byteBuffer.Length; i++) { int randChar = rndGen.Next(0, 128); byteBuffer[i] = (byte)randChar; charBuffer[i] = (char)randChar; } if (-1 == parityReplace) { //If parityReplace is -1 and we should just use the default value expectedChar = com1.ParityReplace; } else if ('\0' == parityReplace) { //If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedChar = charBuffer[parityErrorIndex]; } else { //Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedChar = parityReplace; } //Create an parity error by setting the highest order bit to true byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); charBuffer[parityErrorIndex] = (char)expectedChar; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Open(); com2.Open(); VerifyRead(com1, com2, byteBuffer, charBuffer); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] charRcvBuffer = new char[expectedChars.Length]; int rcvBufferSize = 0; int i; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); i = 0; while (true) { int readInt; try { readInt = com1.ReadChar(); } catch (TimeoutException) { break; } //While their are more characters to be read if (expectedChars.Length <= i) { //If we have read in more characters then we expecte Fail("ERROR!!!: We have received more characters then were sent"); } charRcvBuffer[i] = (char)readInt; rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1); if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); } if (readInt != expectedChars[i]) { //If the character read is not the expected character Fail("ERROR!!!: Expected to read {0} actual read char {1}", expectedChars[i], (char)readInt); } i++; } Assert.Equal(expectedChars.Length, i); } #endregion } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_compiler.h" #include "opensslshim.h" /* Shims the EVP_PKEY_new method. Returns the new EVP_PKEY instance. */ PALEXPORT EVP_PKEY* CryptoNative_EvpPkeyCreate(void); /* Create a new EVP_PKEY that has the same interior key as currentKey, optionally verifying that the key has the correct algorithm. */ PALEXPORT EVP_PKEY* CryptoNative_EvpPKeyDuplicate(EVP_PKEY* currentKey, int32_t algId); /* Cleans up and deletes a EVP_PKEY instance. Implemented by calling EVP_PKEY_free. No-op if pkey is null. The given EVP_PKEY pointer is invalid after this call. Always succeeds. */ PALEXPORT void CryptoNative_EvpPkeyDestroy(EVP_PKEY* pkey); /* Returns the maximum size, in bytes, of an operation with the provided key. */ PALEXPORT int32_t CryptoNative_EvpPKeySize(EVP_PKEY* pkey); /* Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader when duplicating a private key context as part of duplicating the Pal object. Returns the number (as of this call) of references to the EVP_PKEY. Anything less than 2 is an error, because the key is already in the process of being freed. */ PALEXPORT int32_t CryptoNative_UpRefEvpPkey(EVP_PKEY* pkey); /* Decodes an X.509 SubjectPublicKeyInfo into an EVP_PKEY*, verifying the interpreted algorithm type. Requres a non-null buf, and len > 0. */ PALEXPORT EVP_PKEY* CryptoNative_DecodeSubjectPublicKeyInfo(const uint8_t* buf, int32_t len, int32_t algId); /* Decodes an Pkcs8PrivateKeyInfo into an EVP_PKEY*, verifying the interpreted algorithm type. Requres a non-null buf, and len > 0. */ PALEXPORT EVP_PKEY* CryptoNative_DecodePkcs8PrivateKey(const uint8_t* buf, int32_t len, int32_t algId); /* Gets the number of bytes rqeuired to encode an EVP_PKEY* as a Pkcs8PrivateKeyInfo. On success, 1 is returned and p8size contains the size of the Pkcs8PrivateKeyInfo. On failure, -1 is used to indicate the openssl error queue contains the error. On failure, -2 is used to indcate that the supplied EVP_PKEY* is possibly missing a private key. */ PALEXPORT int32_t CryptoNative_GetPkcs8PrivateKeySize(EVP_PKEY* pkey, int32_t* p8size); /* Encodes the EVP_PKEY* as a Pkcs8PrivateKeyInfo, writing the encoded value to buf. buf must be big enough, or an out of bounds write may occur. Returns the number of bytes written. */ PALEXPORT int32_t CryptoNative_EncodePkcs8PrivateKey(EVP_PKEY* pkey, uint8_t* buf); /* Reports the number of bytes rqeuired to encode an EVP_PKEY* as an X.509 SubjectPublicKeyInfo, or a negative value on error. */ PALEXPORT int32_t CryptoNative_GetSubjectPublicKeyInfoSize(EVP_PKEY* pkey); /* Encodes the EVP_PKEY* as an X.509 SubjectPublicKeyInfo, writing the encoded value to buf. buf must be big enough, or an out of bounds write may occur. Returns the number of bytes written. */ PALEXPORT int32_t CryptoNative_EncodeSubjectPublicKeyInfo(EVP_PKEY* pkey, uint8_t* buf);
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_types.h" #include "pal_compiler.h" #include "opensslshim.h" /* Shims the EVP_PKEY_new method. Returns the new EVP_PKEY instance. */ PALEXPORT EVP_PKEY* CryptoNative_EvpPkeyCreate(void); /* Create a new EVP_PKEY that has the same interior key as currentKey, optionally verifying that the key has the correct algorithm. */ PALEXPORT EVP_PKEY* CryptoNative_EvpPKeyDuplicate(EVP_PKEY* currentKey, int32_t algId); /* Cleans up and deletes a EVP_PKEY instance. Implemented by calling EVP_PKEY_free. No-op if pkey is null. The given EVP_PKEY pointer is invalid after this call. Always succeeds. */ PALEXPORT void CryptoNative_EvpPkeyDestroy(EVP_PKEY* pkey); /* Returns the maximum size, in bytes, of an operation with the provided key. */ PALEXPORT int32_t CryptoNative_EvpPKeySize(EVP_PKEY* pkey); /* Used by System.Security.Cryptography.X509Certificates' OpenSslX509CertificateReader when duplicating a private key context as part of duplicating the Pal object. Returns the number (as of this call) of references to the EVP_PKEY. Anything less than 2 is an error, because the key is already in the process of being freed. */ PALEXPORT int32_t CryptoNative_UpRefEvpPkey(EVP_PKEY* pkey); /* Decodes an X.509 SubjectPublicKeyInfo into an EVP_PKEY*, verifying the interpreted algorithm type. Requres a non-null buf, and len > 0. */ PALEXPORT EVP_PKEY* CryptoNative_DecodeSubjectPublicKeyInfo(const uint8_t* buf, int32_t len, int32_t algId); /* Decodes an Pkcs8PrivateKeyInfo into an EVP_PKEY*, verifying the interpreted algorithm type. Requres a non-null buf, and len > 0. */ PALEXPORT EVP_PKEY* CryptoNative_DecodePkcs8PrivateKey(const uint8_t* buf, int32_t len, int32_t algId); /* Gets the number of bytes rqeuired to encode an EVP_PKEY* as a Pkcs8PrivateKeyInfo. On success, 1 is returned and p8size contains the size of the Pkcs8PrivateKeyInfo. On failure, -1 is used to indicate the openssl error queue contains the error. On failure, -2 is used to indcate that the supplied EVP_PKEY* is possibly missing a private key. */ PALEXPORT int32_t CryptoNative_GetPkcs8PrivateKeySize(EVP_PKEY* pkey, int32_t* p8size); /* Encodes the EVP_PKEY* as a Pkcs8PrivateKeyInfo, writing the encoded value to buf. buf must be big enough, or an out of bounds write may occur. Returns the number of bytes written. */ PALEXPORT int32_t CryptoNative_EncodePkcs8PrivateKey(EVP_PKEY* pkey, uint8_t* buf); /* Reports the number of bytes rqeuired to encode an EVP_PKEY* as an X.509 SubjectPublicKeyInfo, or a negative value on error. */ PALEXPORT int32_t CryptoNative_GetSubjectPublicKeyInfoSize(EVP_PKEY* pkey); /* Encodes the EVP_PKEY* as an X.509 SubjectPublicKeyInfo, writing the encoded value to buf. buf must be big enough, or an out of bounds write may occur. Returns the number of bytes written. */ PALEXPORT int32_t CryptoNative_EncodeSubjectPublicKeyInfo(EVP_PKEY* pkey, uint8_t* buf);
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/Microsoft.Extensions.FileProviders.Composite/tests/MockFileInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; namespace Microsoft.Extensions.FileProviders.Composite { public class MockFileInfo : IFileInfo { public MockFileInfo(string name) { Name = name; } public bool Exists { get { return true; } } public bool IsDirectory { get; set; } public DateTimeOffset LastModified { get; set; } public long Length { get; set; } public string Name { get; } public string PhysicalPath { get; set; } public Stream CreateReadStream() { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; namespace Microsoft.Extensions.FileProviders.Composite { public class MockFileInfo : IFileInfo { public MockFileInfo(string name) { Name = name; } public bool Exists { get { return true; } } public bool IsDirectory { get; set; } public DateTimeOffset LastModified { get; set; } public long Length { get; set; } public string Name { get; } public string PhysicalPath { get; set; } public Stream CreateReadStream() { throw new NotImplementedException(); } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/example_xhtml_summary1.xml
<!-- Description: Example atom:summary with xhtml content Expect: !Error --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml"> This is <b>XHTML</b> content. </div> </summary> </entry> </feed>
<!-- Description: Example atom:summary with xhtml content Expect: !Error --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml"> This is <b>XHTML</b> content. </div> </summary> </entry> </feed>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/coreclr/System.Private.CoreLib/src/System/Reflection/MethodInvoker.CoreCLR.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Reflection { internal partial class MethodInvoker { private readonly Signature _signature; internal InvocationFlags _invocationFlags; public MethodInvoker(MethodBase method, Signature signature) { _method = method; _signature = signature; #if USE_NATIVE_INVOKE // Always use the native invoke; useful for testing. _strategyDetermined = true; #elif USE_EMIT_INVOKE // Always use emit invoke (if IsDynamicCodeCompiled == true); useful for testing. _invoked = true; #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe object? InterpretedInvoke(object? obj, IntPtr* arguments) { return RuntimeMethodHandle.InvokeMethod(obj, (void**)arguments, _signature, isConstructor: 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.Runtime.CompilerServices; namespace System.Reflection { internal partial class MethodInvoker { private readonly Signature _signature; internal InvocationFlags _invocationFlags; public MethodInvoker(MethodBase method, Signature signature) { _method = method; _signature = signature; #if USE_NATIVE_INVOKE // Always use the native invoke; useful for testing. _strategyDetermined = true; #elif USE_EMIT_INVOKE // Always use emit invoke (if IsDynamicCodeCompiled == true); useful for testing. _invoked = true; #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe object? InterpretedInvoke(object? obj, IntPtr* arguments) { return RuntimeMethodHandle.InvokeMethod(obj, (void**)arguments, _signature, isConstructor: false); } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/ceq_r8.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ceq_r8.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ceq_r8.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Text.Encoding.CodePages/src/Data/Tools/EncodingDataGenerator.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> </PropertyGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/coreclr/pal/src/include/pal/thread.hpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: include/pal/thread.hpp Abstract: Header file for thread structures --*/ #ifndef _PAL_THREAD_HPP_ #define _PAL_THREAD_HPP_ #include "corunix.hpp" #include "shm.hpp" #include "cs.hpp" #include <pthread.h> #include <sys/syscall.h> #if HAVE_MACH_EXCEPTIONS #include <mach/mach.h> #endif // HAVE_MACH_EXCEPTIONS #include "threadsusp.hpp" #include "threadinfo.hpp" #include "synchobjects.hpp" #include <errno.h> namespace CorUnix { enum PalThreadType { UserCreatedThread, PalWorkerThread, SignalHandlerThread }; PAL_ERROR InternalCreateThread( CPalThread *pThread, LPSECURITY_ATTRIBUTES lpThreadAttributes, DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, PalThreadType eThreadType, SIZE_T* pThreadId, HANDLE *phThread ); PAL_ERROR InternalGetThreadPriority( CPalThread *pThread, HANDLE hTargetThread, int *piNewPriority ); PAL_ERROR InternalSetThreadPriority( CPalThread *pThread, HANDLE hTargetThread, int iNewPriority ); PAL_ERROR InternalGetThreadDataFromHandle( CPalThread *pThread, HANDLE hThread, CPalThread **ppTargetThread, IPalObject **ppobjThread ); VOID InternalEndCurrentThread( CPalThread *pThread ); PAL_ERROR InternalCreateDummyThread( CPalThread *pThread, LPSECURITY_ATTRIBUTES lpThreadAttributes, CPalThread **ppDummyThread, HANDLE *phThread ); PAL_ERROR InternalSetThreadDescription( CPalThread *, HANDLE, PCWSTR ); PAL_ERROR CreateThreadData( CPalThread **ppThread ); PAL_ERROR CreateThreadObject( CPalThread *pThread, CPalThread *pNewThread, HANDLE *phThread ); BOOL GetThreadTimesInternal( IN HANDLE hThread, OUT LPFILETIME lpKernelTime, OUT LPFILETIME lpUserTime); #if HAVE_MACH_EXCEPTIONS // Structure used to return data about a single handler to a caller. struct MachExceptionHandler { exception_mask_t m_mask; exception_handler_t m_handler; exception_behavior_t m_behavior; thread_state_flavor_t m_flavor; }; // Class abstracting previously registered Mach exception handlers for a thread. struct CThreadMachExceptionHandlers { public: // Maximum number of exception ports we hook. Must be the count // of all bits set in the exception masks defined in machexception.h. static const int s_nPortsMax = 6; // Saved exception ports, exactly as returned by // thread_swap_exception_ports. mach_msg_type_number_t m_nPorts; exception_mask_t m_masks[s_nPortsMax]; exception_handler_t m_handlers[s_nPortsMax]; exception_behavior_t m_behaviors[s_nPortsMax]; thread_state_flavor_t m_flavors[s_nPortsMax]; CThreadMachExceptionHandlers() : m_nPorts(-1) { } // Get handler details for a given type of exception. If successful the structure pointed at by // pHandler is filled in and true is returned. Otherwise false is returned. bool GetHandler(exception_type_t eException, MachExceptionHandler *pHandler); private: // Look for a handler for the given exception within the given handler node. Return its index if // successful or -1 otherwise. int GetIndexOfHandler(exception_mask_t bmExceptionMask); }; #endif // HAVE_MACH_EXCEPTIONS class CThreadCRTInfo : public CThreadInfoInitializer { public: CHAR * strtokContext; // Context for strtok function WCHAR * wcstokContext; // Context for wcstok function CThreadCRTInfo() : strtokContext(NULL), wcstokContext(NULL) { }; }; class CPalThread { friend PAL_ERROR InternalCreateThread( CPalThread *, LPSECURITY_ATTRIBUTES, DWORD, LPTHREAD_START_ROUTINE, LPVOID, DWORD, PalThreadType, SIZE_T*, HANDLE* ); friend PAL_ERROR InternalCreateDummyThread( CPalThread *pThread, LPSECURITY_ATTRIBUTES lpThreadAttributes, CPalThread **ppDummyThread, HANDLE *phThread ); friend PAL_ERROR InternalSetThreadPriority( CPalThread *, HANDLE, int ); friend PAL_ERROR InternalSetThreadDescription( CPalThread *, HANDLE, PCWSTR ); friend PAL_ERROR CreateThreadData( CPalThread **ppThread ); friend PAL_ERROR CreateThreadObject( CPalThread *pThread, CPalThread *pNewThread, HANDLE *phThread ); private: CPalThread *m_pNext; DWORD m_dwExitCode; BOOL m_fExitCodeSet; CRITICAL_SECTION m_csLock; bool m_fLockInitialized; bool m_fIsDummy; // // Minimal reference count, used primarily for cleanup purposes. A // new thread object has an initial refcount of 1. This initial // reference is removed by CorUnix::InternalEndCurrentThread. // // The only other spot the refcount is touched is from within // CPalObjectBase::ReleaseReference -- incremented before the // destructors for an ojbect are called, and decremented afterwords. // This permits the freeing of the thread structure to happen after // the freeing of the enclosing thread object has completed. // LONG m_lRefCount; // // The IPalObject for this thread. The thread will release its reference // to this object when it exits. // IPalObject *m_pThreadObject; // // Thread ID info // SIZE_T m_threadId; DWORD m_dwLwpId; pthread_t m_pthreadSelf; #if HAVE_MACH_THREADS mach_port_t m_machPortSelf; #endif // > 0 when there is an exception holder which causes h/w // exceptions to be sent down the C++ exception chain. int m_hardwareExceptionHolderCount; // // Start info // LPTHREAD_START_ROUTINE m_lpStartAddress; LPVOID m_lpStartParameter; BOOL m_bCreateSuspended; int m_iThreadPriority; PalThreadType m_eThreadType; // // pthread mutex / condition variable for gating thread startup. // InternalCreateThread waits on the condition variable to determine // when the new thread has reached passed all failure points in // the entry routine // pthread_mutex_t m_startMutex; pthread_cond_t m_startCond; bool m_fStartItemsInitialized; bool m_fStartStatus; bool m_fStartStatusSet; // Base address of the stack of this thread void* m_stackBase; // Limit address of the stack of this thread void* m_stackLimit; // Signal handler's alternate stack to help with stack overflow void* m_alternateStack; // // The thread entry routine (called from InternalCreateThread) // static void* ThreadEntry(void * pvParam); // // Data for PAL side-by-side support // private: #if HAVE_MACH_EXCEPTIONS // Record of Mach exception handlers that were already registered when we register our own CoreCLR // specific handlers. CThreadMachExceptionHandlers m_sMachExceptionHandlers; #endif // HAVE_MACH_EXCEPTIONS public: // // Embedded information for areas owned by other subsystems // CThreadSynchronizationInfo synchronizationInfo; CThreadSuspensionInfo suspensionInfo; CThreadApcInfo apcInfo; CThreadCRTInfo crtInfo; CPalThread() : m_pNext(NULL), m_dwExitCode(STILL_ACTIVE), m_fExitCodeSet(FALSE), m_fLockInitialized(FALSE), m_fIsDummy(FALSE), m_lRefCount(1), m_pThreadObject(NULL), m_threadId(0), m_dwLwpId(0), m_pthreadSelf(0), #if HAVE_MACH_THREADS m_machPortSelf(0), #endif m_hardwareExceptionHolderCount(0), m_lpStartAddress(NULL), m_lpStartParameter(NULL), m_bCreateSuspended(FALSE), m_iThreadPriority(THREAD_PRIORITY_NORMAL), m_eThreadType(UserCreatedThread), m_fStartItemsInitialized(FALSE), m_fStartStatus(FALSE), m_fStartStatusSet(FALSE), m_stackBase(NULL), m_stackLimit(NULL), m_alternateStack(NULL) { }; virtual ~CPalThread(); PAL_ERROR RunPreCreateInitializers( void ); // // m_threadId and m_dwLwpId must be set before calling // RunPostCreateInitializers // PAL_ERROR RunPostCreateInitializers( void ); // // SetStartStatus is called by THREADEntry or InternalSuspendNewThread // to inform InternalCreateThread of the results of the thread's // initialization. InternalCreateThread calls WaitForStartStatus to // obtain this information (and will not return to its caller until // the info is available). // void SetStartStatus( bool fStartSucceeded ); bool WaitForStartStatus( void ); void Lock( CPalThread *pThread ) { InternalEnterCriticalSection(pThread, &m_csLock); }; void Unlock( CPalThread *pThread ) { InternalLeaveCriticalSection(pThread, &m_csLock); }; // // The following three methods provide access to the // native lock used to protect thread native wait data. // void AcquireNativeWaitLock( void ) { synchronizationInfo.AcquireNativeWaitLock(); } void ReleaseNativeWaitLock( void ) { synchronizationInfo.ReleaseNativeWaitLock(); } bool TryAcquireNativeWaitLock( void ) { return synchronizationInfo.TryAcquireNativeWaitLock(); } static void SetLastError( DWORD dwLastError ) { // Reuse errno to store last error errno = dwLastError; }; static DWORD GetLastError( void ) { // Reuse errno to store last error return errno; }; void SetExitCode( DWORD dwExitCode ) { m_dwExitCode = dwExitCode; m_fExitCodeSet = TRUE; }; BOOL GetExitCode( DWORD *pdwExitCode ) { *pdwExitCode = m_dwExitCode; return m_fExitCodeSet; }; SIZE_T GetThreadId( void ) { return m_threadId; }; DWORD GetLwpId( void ) { return m_dwLwpId; }; pthread_t GetPThreadSelf( void ) { return m_pthreadSelf; }; #if HAVE_MACH_THREADS mach_port_t GetMachPortSelf( void ) { return m_machPortSelf; }; #endif bool IsHardwareExceptionsEnabled() { return m_hardwareExceptionHolderCount > 0; } inline void IncrementHardwareExceptionHolderCount() { ++m_hardwareExceptionHolderCount; } inline void DecrementHardwareExceptionHolderCount() { --m_hardwareExceptionHolderCount; } LPTHREAD_START_ROUTINE GetStartAddress( void ) { return m_lpStartAddress; }; LPVOID GetStartParameter( void ) { return m_lpStartParameter; }; BOOL GetCreateSuspended( void ) { return m_bCreateSuspended; }; PalThreadType GetThreadType( void ) { return m_eThreadType; }; int GetThreadPriority( void ) { return m_iThreadPriority; }; IPalObject * GetThreadObject( void ) { return m_pThreadObject; } BOOL IsDummy( void ) { return m_fIsDummy; }; CPalThread* GetNext( void ) { return m_pNext; }; void SetNext( CPalThread *pNext ) { m_pNext = pNext; }; #if !HAVE_MACH_EXCEPTIONS BOOL EnsureSignalAlternateStack( void ); void FreeSignalAlternateStack( void ); #endif // !HAVE_MACH_EXCEPTIONS void AddThreadReference( void ); void ReleaseThreadReference( void ); // Get base address of the current thread's stack static void * GetStackBase( void ); // Get cached base address of this thread's stack // Can be called only for the current thread. void * GetCachedStackBase( void ); // Get limit address of the current thread's stack static void * GetStackLimit( void ); // Get cached limit address of this thread's stack // Can be called only for the current thread. void * GetCachedStackLimit( void ); #if HAVE_MACH_EXCEPTIONS // Hook Mach exceptions, i.e., call thread_swap_exception_ports // to replace the thread's current exception ports with our own. // The previously active exception ports are saved. Called when // this thread enters a region of code that depends on this PAL. // Should only fail on internal errors. PAL_ERROR EnableMachExceptions(); // Unhook Mach exceptions, i.e., call thread_set_exception_ports // to restore the thread's exception ports with those we saved // in EnableMachExceptions. Called when this thread leaves a // region of code that depends on this PAL. Should only fail // on internal errors. PAL_ERROR DisableMachExceptions(); // The exception handling thread needs to be able to get at the list of handlers that installing our // own handler on a thread has displaced (in case we need to forward an exception that we don't want // to handle). CThreadMachExceptionHandlers *GetSavedMachHandlers() { return &m_sMachExceptionHandlers; } #endif // HAVE_MACH_EXCEPTIONS }; extern "C" CPalThread *CreateCurrentThreadData(); inline CPalThread *GetCurrentPalThread() { return reinterpret_cast<CPalThread*>(pthread_getspecific(thObjKey)); } inline CPalThread *InternalGetCurrentThread() { CPalThread *pThread = GetCurrentPalThread(); if (pThread == nullptr) pThread = CreateCurrentThreadData(); return pThread; } /*** $$TODO: These are needed only to support cross-process thread duplication class CThreadImmutableData { public: DWORD dwProcessId; }; class CThreadSharedData { public: DWORD dwThreadId; DWORD dwExitCode; }; ***/ // // The process local information for a thread is just a pointer // to the underlying CPalThread object. // class CThreadProcessLocalData { public: CPalThread *pThread; }; extern CObjectType otThread; } BOOL TLSInitialize( void ); VOID TLSCleanup( void ); extern PAL_ActivationFunction g_activationFunction; extern PAL_SafeActivationCheckFunction g_safeActivationCheckFunction; /*++ Macro: THREADSilentGetCurrentThreadId Abstract: Same as GetCurrentThreadId, but it doesn't output any traces. It is useful for tracing functions to display the thread ID without generating any new traces. TODO: how does the perf of pthread_self compare to InternalGetCurrentThread when we find the thread in the cache? If the perf of pthread_self is comparable to that of the stack bounds based lookaside system, why aren't we using it in the cache? In order to match the thread ids that debuggers use at least for linux we need to use gettid(). --*/ #if defined(__linux__) #define PlatformGetCurrentThreadId() (SIZE_T)syscall(SYS_gettid) #elif defined(__APPLE__) inline SIZE_T PlatformGetCurrentThreadId() { uint64_t tid; pthread_threadid_np(pthread_self(), &tid); return (SIZE_T)tid; } #elif defined(__FreeBSD__) #include <pthread_np.h> #define PlatformGetCurrentThreadId() (SIZE_T)pthread_getthreadid_np() #elif defined(__NetBSD__) #include <lwp.h> #define PlatformGetCurrentThreadId() (SIZE_T)_lwp_self() #else #define PlatformGetCurrentThreadId() (SIZE_T)pthread_self() #endif inline SIZE_T THREADSilentGetCurrentThreadId() { static __thread SIZE_T tid; if (!tid) tid = PlatformGetCurrentThreadId(); return tid; } #endif // _PAL_THREAD_HPP_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: include/pal/thread.hpp Abstract: Header file for thread structures --*/ #ifndef _PAL_THREAD_HPP_ #define _PAL_THREAD_HPP_ #include "corunix.hpp" #include "shm.hpp" #include "cs.hpp" #include <pthread.h> #include <sys/syscall.h> #if HAVE_MACH_EXCEPTIONS #include <mach/mach.h> #endif // HAVE_MACH_EXCEPTIONS #include "threadsusp.hpp" #include "threadinfo.hpp" #include "synchobjects.hpp" #include <errno.h> namespace CorUnix { enum PalThreadType { UserCreatedThread, PalWorkerThread, SignalHandlerThread }; PAL_ERROR InternalCreateThread( CPalThread *pThread, LPSECURITY_ATTRIBUTES lpThreadAttributes, DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, PalThreadType eThreadType, SIZE_T* pThreadId, HANDLE *phThread ); PAL_ERROR InternalGetThreadPriority( CPalThread *pThread, HANDLE hTargetThread, int *piNewPriority ); PAL_ERROR InternalSetThreadPriority( CPalThread *pThread, HANDLE hTargetThread, int iNewPriority ); PAL_ERROR InternalGetThreadDataFromHandle( CPalThread *pThread, HANDLE hThread, CPalThread **ppTargetThread, IPalObject **ppobjThread ); VOID InternalEndCurrentThread( CPalThread *pThread ); PAL_ERROR InternalCreateDummyThread( CPalThread *pThread, LPSECURITY_ATTRIBUTES lpThreadAttributes, CPalThread **ppDummyThread, HANDLE *phThread ); PAL_ERROR InternalSetThreadDescription( CPalThread *, HANDLE, PCWSTR ); PAL_ERROR CreateThreadData( CPalThread **ppThread ); PAL_ERROR CreateThreadObject( CPalThread *pThread, CPalThread *pNewThread, HANDLE *phThread ); BOOL GetThreadTimesInternal( IN HANDLE hThread, OUT LPFILETIME lpKernelTime, OUT LPFILETIME lpUserTime); #if HAVE_MACH_EXCEPTIONS // Structure used to return data about a single handler to a caller. struct MachExceptionHandler { exception_mask_t m_mask; exception_handler_t m_handler; exception_behavior_t m_behavior; thread_state_flavor_t m_flavor; }; // Class abstracting previously registered Mach exception handlers for a thread. struct CThreadMachExceptionHandlers { public: // Maximum number of exception ports we hook. Must be the count // of all bits set in the exception masks defined in machexception.h. static const int s_nPortsMax = 6; // Saved exception ports, exactly as returned by // thread_swap_exception_ports. mach_msg_type_number_t m_nPorts; exception_mask_t m_masks[s_nPortsMax]; exception_handler_t m_handlers[s_nPortsMax]; exception_behavior_t m_behaviors[s_nPortsMax]; thread_state_flavor_t m_flavors[s_nPortsMax]; CThreadMachExceptionHandlers() : m_nPorts(-1) { } // Get handler details for a given type of exception. If successful the structure pointed at by // pHandler is filled in and true is returned. Otherwise false is returned. bool GetHandler(exception_type_t eException, MachExceptionHandler *pHandler); private: // Look for a handler for the given exception within the given handler node. Return its index if // successful or -1 otherwise. int GetIndexOfHandler(exception_mask_t bmExceptionMask); }; #endif // HAVE_MACH_EXCEPTIONS class CThreadCRTInfo : public CThreadInfoInitializer { public: CHAR * strtokContext; // Context for strtok function WCHAR * wcstokContext; // Context for wcstok function CThreadCRTInfo() : strtokContext(NULL), wcstokContext(NULL) { }; }; class CPalThread { friend PAL_ERROR InternalCreateThread( CPalThread *, LPSECURITY_ATTRIBUTES, DWORD, LPTHREAD_START_ROUTINE, LPVOID, DWORD, PalThreadType, SIZE_T*, HANDLE* ); friend PAL_ERROR InternalCreateDummyThread( CPalThread *pThread, LPSECURITY_ATTRIBUTES lpThreadAttributes, CPalThread **ppDummyThread, HANDLE *phThread ); friend PAL_ERROR InternalSetThreadPriority( CPalThread *, HANDLE, int ); friend PAL_ERROR InternalSetThreadDescription( CPalThread *, HANDLE, PCWSTR ); friend PAL_ERROR CreateThreadData( CPalThread **ppThread ); friend PAL_ERROR CreateThreadObject( CPalThread *pThread, CPalThread *pNewThread, HANDLE *phThread ); private: CPalThread *m_pNext; DWORD m_dwExitCode; BOOL m_fExitCodeSet; CRITICAL_SECTION m_csLock; bool m_fLockInitialized; bool m_fIsDummy; // // Minimal reference count, used primarily for cleanup purposes. A // new thread object has an initial refcount of 1. This initial // reference is removed by CorUnix::InternalEndCurrentThread. // // The only other spot the refcount is touched is from within // CPalObjectBase::ReleaseReference -- incremented before the // destructors for an ojbect are called, and decremented afterwords. // This permits the freeing of the thread structure to happen after // the freeing of the enclosing thread object has completed. // LONG m_lRefCount; // // The IPalObject for this thread. The thread will release its reference // to this object when it exits. // IPalObject *m_pThreadObject; // // Thread ID info // SIZE_T m_threadId; DWORD m_dwLwpId; pthread_t m_pthreadSelf; #if HAVE_MACH_THREADS mach_port_t m_machPortSelf; #endif // > 0 when there is an exception holder which causes h/w // exceptions to be sent down the C++ exception chain. int m_hardwareExceptionHolderCount; // // Start info // LPTHREAD_START_ROUTINE m_lpStartAddress; LPVOID m_lpStartParameter; BOOL m_bCreateSuspended; int m_iThreadPriority; PalThreadType m_eThreadType; // // pthread mutex / condition variable for gating thread startup. // InternalCreateThread waits on the condition variable to determine // when the new thread has reached passed all failure points in // the entry routine // pthread_mutex_t m_startMutex; pthread_cond_t m_startCond; bool m_fStartItemsInitialized; bool m_fStartStatus; bool m_fStartStatusSet; // Base address of the stack of this thread void* m_stackBase; // Limit address of the stack of this thread void* m_stackLimit; // Signal handler's alternate stack to help with stack overflow void* m_alternateStack; // // The thread entry routine (called from InternalCreateThread) // static void* ThreadEntry(void * pvParam); // // Data for PAL side-by-side support // private: #if HAVE_MACH_EXCEPTIONS // Record of Mach exception handlers that were already registered when we register our own CoreCLR // specific handlers. CThreadMachExceptionHandlers m_sMachExceptionHandlers; #endif // HAVE_MACH_EXCEPTIONS public: // // Embedded information for areas owned by other subsystems // CThreadSynchronizationInfo synchronizationInfo; CThreadSuspensionInfo suspensionInfo; CThreadApcInfo apcInfo; CThreadCRTInfo crtInfo; CPalThread() : m_pNext(NULL), m_dwExitCode(STILL_ACTIVE), m_fExitCodeSet(FALSE), m_fLockInitialized(FALSE), m_fIsDummy(FALSE), m_lRefCount(1), m_pThreadObject(NULL), m_threadId(0), m_dwLwpId(0), m_pthreadSelf(0), #if HAVE_MACH_THREADS m_machPortSelf(0), #endif m_hardwareExceptionHolderCount(0), m_lpStartAddress(NULL), m_lpStartParameter(NULL), m_bCreateSuspended(FALSE), m_iThreadPriority(THREAD_PRIORITY_NORMAL), m_eThreadType(UserCreatedThread), m_fStartItemsInitialized(FALSE), m_fStartStatus(FALSE), m_fStartStatusSet(FALSE), m_stackBase(NULL), m_stackLimit(NULL), m_alternateStack(NULL) { }; virtual ~CPalThread(); PAL_ERROR RunPreCreateInitializers( void ); // // m_threadId and m_dwLwpId must be set before calling // RunPostCreateInitializers // PAL_ERROR RunPostCreateInitializers( void ); // // SetStartStatus is called by THREADEntry or InternalSuspendNewThread // to inform InternalCreateThread of the results of the thread's // initialization. InternalCreateThread calls WaitForStartStatus to // obtain this information (and will not return to its caller until // the info is available). // void SetStartStatus( bool fStartSucceeded ); bool WaitForStartStatus( void ); void Lock( CPalThread *pThread ) { InternalEnterCriticalSection(pThread, &m_csLock); }; void Unlock( CPalThread *pThread ) { InternalLeaveCriticalSection(pThread, &m_csLock); }; // // The following three methods provide access to the // native lock used to protect thread native wait data. // void AcquireNativeWaitLock( void ) { synchronizationInfo.AcquireNativeWaitLock(); } void ReleaseNativeWaitLock( void ) { synchronizationInfo.ReleaseNativeWaitLock(); } bool TryAcquireNativeWaitLock( void ) { return synchronizationInfo.TryAcquireNativeWaitLock(); } static void SetLastError( DWORD dwLastError ) { // Reuse errno to store last error errno = dwLastError; }; static DWORD GetLastError( void ) { // Reuse errno to store last error return errno; }; void SetExitCode( DWORD dwExitCode ) { m_dwExitCode = dwExitCode; m_fExitCodeSet = TRUE; }; BOOL GetExitCode( DWORD *pdwExitCode ) { *pdwExitCode = m_dwExitCode; return m_fExitCodeSet; }; SIZE_T GetThreadId( void ) { return m_threadId; }; DWORD GetLwpId( void ) { return m_dwLwpId; }; pthread_t GetPThreadSelf( void ) { return m_pthreadSelf; }; #if HAVE_MACH_THREADS mach_port_t GetMachPortSelf( void ) { return m_machPortSelf; }; #endif bool IsHardwareExceptionsEnabled() { return m_hardwareExceptionHolderCount > 0; } inline void IncrementHardwareExceptionHolderCount() { ++m_hardwareExceptionHolderCount; } inline void DecrementHardwareExceptionHolderCount() { --m_hardwareExceptionHolderCount; } LPTHREAD_START_ROUTINE GetStartAddress( void ) { return m_lpStartAddress; }; LPVOID GetStartParameter( void ) { return m_lpStartParameter; }; BOOL GetCreateSuspended( void ) { return m_bCreateSuspended; }; PalThreadType GetThreadType( void ) { return m_eThreadType; }; int GetThreadPriority( void ) { return m_iThreadPriority; }; IPalObject * GetThreadObject( void ) { return m_pThreadObject; } BOOL IsDummy( void ) { return m_fIsDummy; }; CPalThread* GetNext( void ) { return m_pNext; }; void SetNext( CPalThread *pNext ) { m_pNext = pNext; }; #if !HAVE_MACH_EXCEPTIONS BOOL EnsureSignalAlternateStack( void ); void FreeSignalAlternateStack( void ); #endif // !HAVE_MACH_EXCEPTIONS void AddThreadReference( void ); void ReleaseThreadReference( void ); // Get base address of the current thread's stack static void * GetStackBase( void ); // Get cached base address of this thread's stack // Can be called only for the current thread. void * GetCachedStackBase( void ); // Get limit address of the current thread's stack static void * GetStackLimit( void ); // Get cached limit address of this thread's stack // Can be called only for the current thread. void * GetCachedStackLimit( void ); #if HAVE_MACH_EXCEPTIONS // Hook Mach exceptions, i.e., call thread_swap_exception_ports // to replace the thread's current exception ports with our own. // The previously active exception ports are saved. Called when // this thread enters a region of code that depends on this PAL. // Should only fail on internal errors. PAL_ERROR EnableMachExceptions(); // Unhook Mach exceptions, i.e., call thread_set_exception_ports // to restore the thread's exception ports with those we saved // in EnableMachExceptions. Called when this thread leaves a // region of code that depends on this PAL. Should only fail // on internal errors. PAL_ERROR DisableMachExceptions(); // The exception handling thread needs to be able to get at the list of handlers that installing our // own handler on a thread has displaced (in case we need to forward an exception that we don't want // to handle). CThreadMachExceptionHandlers *GetSavedMachHandlers() { return &m_sMachExceptionHandlers; } #endif // HAVE_MACH_EXCEPTIONS }; extern "C" CPalThread *CreateCurrentThreadData(); inline CPalThread *GetCurrentPalThread() { return reinterpret_cast<CPalThread*>(pthread_getspecific(thObjKey)); } inline CPalThread *InternalGetCurrentThread() { CPalThread *pThread = GetCurrentPalThread(); if (pThread == nullptr) pThread = CreateCurrentThreadData(); return pThread; } /*** $$TODO: These are needed only to support cross-process thread duplication class CThreadImmutableData { public: DWORD dwProcessId; }; class CThreadSharedData { public: DWORD dwThreadId; DWORD dwExitCode; }; ***/ // // The process local information for a thread is just a pointer // to the underlying CPalThread object. // class CThreadProcessLocalData { public: CPalThread *pThread; }; extern CObjectType otThread; } BOOL TLSInitialize( void ); VOID TLSCleanup( void ); extern PAL_ActivationFunction g_activationFunction; extern PAL_SafeActivationCheckFunction g_safeActivationCheckFunction; /*++ Macro: THREADSilentGetCurrentThreadId Abstract: Same as GetCurrentThreadId, but it doesn't output any traces. It is useful for tracing functions to display the thread ID without generating any new traces. TODO: how does the perf of pthread_self compare to InternalGetCurrentThread when we find the thread in the cache? If the perf of pthread_self is comparable to that of the stack bounds based lookaside system, why aren't we using it in the cache? In order to match the thread ids that debuggers use at least for linux we need to use gettid(). --*/ #if defined(__linux__) #define PlatformGetCurrentThreadId() (SIZE_T)syscall(SYS_gettid) #elif defined(__APPLE__) inline SIZE_T PlatformGetCurrentThreadId() { uint64_t tid; pthread_threadid_np(pthread_self(), &tid); return (SIZE_T)tid; } #elif defined(__FreeBSD__) #include <pthread_np.h> #define PlatformGetCurrentThreadId() (SIZE_T)pthread_getthreadid_np() #elif defined(__NetBSD__) #include <lwp.h> #define PlatformGetCurrentThreadId() (SIZE_T)_lwp_self() #else #define PlatformGetCurrentThreadId() (SIZE_T)pthread_self() #endif inline SIZE_T THREADSilentGetCurrentThreadId() { static __thread SIZE_T tid; if (!tid) tid = PlatformGetCurrentThreadId(); return tid; } #endif // _PAL_THREAD_HPP_
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest1268/Generated1268.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated1268 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1740`1<T0> extends class G2_C705`2<class BaseClass0,class BaseClass1> implements class IBase2`2<!T0,class BaseClass0> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1740::Method7.17731<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod4877() cil managed noinlining { ldstr "G3_C1740::ClassMethod4877.17732()" ret } .method public hidebysig newslot virtual instance string ClassMethod4878() cil managed noinlining { ldstr "G3_C1740::ClassMethod4878.17733()" ret } .method public hidebysig newslot virtual instance string ClassMethod4879<M0>() cil managed noinlining { ldstr "G3_C1740::ClassMethod4879.17734<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C705<class BaseClass0,class BaseClass1>.ClassMethod2771'() cil managed noinlining { .override method instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ret } .method public hidebysig newslot virtual instance string 'G2_C705<class BaseClass0,class BaseClass1>.ClassMethod2773'<M0>() cil managed noinlining { .override method instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<[1]>() ldstr "G3_C1740::ClassMethod2773.MI.17736<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C705<class BaseClass0,class BaseClass1>.ClassMethod2774'<M0>() cil managed noinlining { .override method instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<[1]>() ldstr "G3_C1740::ClassMethod2774.MI.17737<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() ret } } .class public G2_C705`2<T0, T1> extends class G1_C13`2<class BaseClass1,class BaseClass1> implements class IBase2`2<class BaseClass1,!T0>, IBase0 { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G2_C705::Method7.11496<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method0() cil managed noinlining { ldstr "G2_C705::Method0.11497()" ret } .method public hidebysig newslot virtual instance string 'IBase0.Method0'() cil managed noinlining { .override method instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ret } .method public hidebysig virtual instance string Method1() cil managed noinlining { ldstr "G2_C705::Method1.11499()" ret } .method public hidebysig newslot virtual instance string 'IBase0.Method1'() cil managed noinlining { .override method instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ret } .method public hidebysig virtual instance string Method2<M0>() cil managed noinlining { ldstr "G2_C705::Method2.11501<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method3<M0>() cil managed noinlining { ldstr "G2_C705::Method3.11502<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2771() cil managed noinlining { ldstr "G2_C705::ClassMethod2771.11503()" ret } .method public hidebysig newslot virtual instance string ClassMethod2772() cil managed noinlining { ldstr "G2_C705::ClassMethod2772.11504()" ret } .method public hidebysig newslot virtual instance string ClassMethod2773<M0>() cil managed noinlining { ldstr "G2_C705::ClassMethod2773.11505<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2774<M0>() cil managed noinlining { ldstr "G2_C705::ClassMethod2774.11506<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C13`2<class BaseClass1,class BaseClass1>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public abstract G1_C13`2<T0, T1> implements class IBase2`2<!T0,!T1>, class IBase1`1<!T0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C13::Method7.4871<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "G1_C13::Method4.4872()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G1_C13::Method5.4873()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G1_C13::Method6.4875<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1348<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1348.4876<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1349<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1349.4877<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase0 { .method public hidebysig newslot abstract virtual instance string Method0() cil managed { } .method public hidebysig newslot abstract virtual instance string Method1() cil managed { } .method public hidebysig newslot abstract virtual instance string Method2<M0>() cil managed { } .method public hidebysig newslot abstract virtual instance string Method3<M0>() cil managed { } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated1268 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1740.T<T0,(class G3_C1740`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 22 .locals init (string[] actualResults) ldc.i4.s 17 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1740.T<T0,(class G3_C1740`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 17 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod4877() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod4878() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod4879<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 14 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 15 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 16 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1740.A<(class G3_C1740`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 22 .locals init (string[] actualResults) ldc.i4.s 17 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1740.A<(class G3_C1740`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 17 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4877() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4878() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4879<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 14 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 15 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 16 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1740.B<(class G3_C1740`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 22 .locals init (string[] actualResults) ldc.i4.s 17 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1740.B<(class G3_C1740`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 17 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4877() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4878() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4879<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 14 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 15 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 16 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.T.T<T0,T1,(class G2_C705`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.T.T<T0,T1,(class G2_C705`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.A.T<T1,(class G2_C705`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.A.T<T1,(class G2_C705`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.A.A<(class G2_C705`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.A.A<(class G2_C705`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.A.B<(class G2_C705`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.A.B<(class G2_C705`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.B.T<T1,(class G2_C705`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.B.T<T1,(class G2_C705`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.B.A<(class G2_C705`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.B.A<(class G2_C705`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.B.B<(class G2_C705`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.B.B<(class G2_C705`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase0<(IBase0)W>(!!W inst, string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase0<(IBase0)W>(!!W inst, string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method3<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1740`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4879<object>() ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4878() ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4877() ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1740`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4879<object>() ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4878() ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4877() ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1740`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.A<class G3_C1740`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1740`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.B<class G3_C1740`1<class BaseClass1>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass1,class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.T<class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.A<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1740`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod4879<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod4878() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod4877() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method1() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method0() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1740`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod4879<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod4878() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod4877() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method1() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method0() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated1268::MethodCallingTest() call void Generated1268::ConstrainedCallsTest() call void Generated1268::StructConstrainedInterfaceCallsTest() call void Generated1268::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated1268 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1740`1<T0> extends class G2_C705`2<class BaseClass0,class BaseClass1> implements class IBase2`2<!T0,class BaseClass0> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1740::Method7.17731<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod4877() cil managed noinlining { ldstr "G3_C1740::ClassMethod4877.17732()" ret } .method public hidebysig newslot virtual instance string ClassMethod4878() cil managed noinlining { ldstr "G3_C1740::ClassMethod4878.17733()" ret } .method public hidebysig newslot virtual instance string ClassMethod4879<M0>() cil managed noinlining { ldstr "G3_C1740::ClassMethod4879.17734<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C705<class BaseClass0,class BaseClass1>.ClassMethod2771'() cil managed noinlining { .override method instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ret } .method public hidebysig newslot virtual instance string 'G2_C705<class BaseClass0,class BaseClass1>.ClassMethod2773'<M0>() cil managed noinlining { .override method instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<[1]>() ldstr "G3_C1740::ClassMethod2773.MI.17736<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C705<class BaseClass0,class BaseClass1>.ClassMethod2774'<M0>() cil managed noinlining { .override method instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<[1]>() ldstr "G3_C1740::ClassMethod2774.MI.17737<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() ret } } .class public G2_C705`2<T0, T1> extends class G1_C13`2<class BaseClass1,class BaseClass1> implements class IBase2`2<class BaseClass1,!T0>, IBase0 { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G2_C705::Method7.11496<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method0() cil managed noinlining { ldstr "G2_C705::Method0.11497()" ret } .method public hidebysig newslot virtual instance string 'IBase0.Method0'() cil managed noinlining { .override method instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ret } .method public hidebysig virtual instance string Method1() cil managed noinlining { ldstr "G2_C705::Method1.11499()" ret } .method public hidebysig newslot virtual instance string 'IBase0.Method1'() cil managed noinlining { .override method instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ret } .method public hidebysig virtual instance string Method2<M0>() cil managed noinlining { ldstr "G2_C705::Method2.11501<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method3<M0>() cil managed noinlining { ldstr "G2_C705::Method3.11502<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2771() cil managed noinlining { ldstr "G2_C705::ClassMethod2771.11503()" ret } .method public hidebysig newslot virtual instance string ClassMethod2772() cil managed noinlining { ldstr "G2_C705::ClassMethod2772.11504()" ret } .method public hidebysig newslot virtual instance string ClassMethod2773<M0>() cil managed noinlining { ldstr "G2_C705::ClassMethod2773.11505<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2774<M0>() cil managed noinlining { ldstr "G2_C705::ClassMethod2774.11506<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C13`2<class BaseClass1,class BaseClass1>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public abstract G1_C13`2<T0, T1> implements class IBase2`2<!T0,!T1>, class IBase1`1<!T0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C13::Method7.4871<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "G1_C13::Method4.4872()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G1_C13::Method5.4873()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G1_C13::Method6.4875<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1348<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1348.4876<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1349<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1349.4877<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase0 { .method public hidebysig newslot abstract virtual instance string Method0() cil managed { } .method public hidebysig newslot abstract virtual instance string Method1() cil managed { } .method public hidebysig newslot abstract virtual instance string Method2<M0>() cil managed { } .method public hidebysig newslot abstract virtual instance string Method3<M0>() cil managed { } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated1268 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1740.T<T0,(class G3_C1740`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 22 .locals init (string[] actualResults) ldc.i4.s 17 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1740.T<T0,(class G3_C1740`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 17 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod4877() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod4878() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::ClassMethod4879<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 14 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 15 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 16 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1740.A<(class G3_C1740`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 22 .locals init (string[] actualResults) ldc.i4.s 17 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1740.A<(class G3_C1740`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 17 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4877() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4878() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4879<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 14 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 15 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 16 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1740.B<(class G3_C1740`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 22 .locals init (string[] actualResults) ldc.i4.s 17 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1740.B<(class G3_C1740`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 17 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4877() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4878() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4879<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 14 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 15 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 16 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1740`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.T.T<T0,T1,(class G2_C705`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.T.T<T0,T1,(class G2_C705`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.A.T<T1,(class G2_C705`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.A.T<T1,(class G2_C705`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.A.A<(class G2_C705`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.A.A<(class G2_C705`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.A.B<(class G2_C705`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.A.B<(class G2_C705`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.B.T<T1,(class G2_C705`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.B.T<T1,(class G2_C705`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.B.A<(class G2_C705`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.B.A<(class G2_C705`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C705.B.B<(class G2_C705`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C705.B.B<(class G2_C705`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2771() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2772() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2773<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2774<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase0<(IBase0)W>(!!W inst, string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase0<(IBase0)W>(!!W inst, string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method3<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1740`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4879<object>() ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4878() ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod4877() ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass0> callvirt instance string class G3_C1740`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1740`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4879<object>() ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4878() ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod4877() ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method7<object>() ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2774<object>() ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2773<object>() ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod2771() ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1740`1<class BaseClass1> callvirt instance string class G3_C1740`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C705`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2774<object>() ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2773<object>() ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2772() ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2771() ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method1() ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method0() ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C705`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1740`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass1,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.B<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G3_C1740`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.T<class BaseClass0,class G3_C1740`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.A<class G3_C1740`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1740`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.B<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G3_C1740`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.T<class BaseClass1,class G3_C1740`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G3_C1740::ClassMethod2771.MI.17735()#G2_C705::ClassMethod2772.11504()#G3_C1740::ClassMethod2773.MI.17736<System.Object>()#G3_C1740::ClassMethod2774.MI.17737<System.Object>()#G3_C1740::ClassMethod4877.17732()#G3_C1740::ClassMethod4878.17733()#G3_C1740::ClassMethod4879.17734<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G3_C1740::Method7.17731<System.Object>()#" call void Generated1268::M.G3_C1740.B<class G3_C1740`1<class BaseClass1>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G2_C705`2<class BaseClass0,class BaseClass0>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.T<class BaseClass1,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.A.B<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.A<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass0,class G2_C705`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.A<class G2_C705`2<class BaseClass0,class BaseClass1>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass1,class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.T<class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.A<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass1,class BaseClass0>>(!!0,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G1_C13.B.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.B.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.IBase2.A.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.T<class BaseClass0,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::Method4.4872()#G1_C13::Method5.MI.4874()#G1_C13::Method6.4875<System.Object>()#" call void Generated1268::M.IBase1.A<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.T.T<class BaseClass1,class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.T<class BaseClass1,class G2_C705`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C13::ClassMethod1348.4876<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C705::ClassMethod2771.11503()#G2_C705::ClassMethod2772.11504()#G2_C705::ClassMethod2773.11505<System.Object>()#G2_C705::ClassMethod2774.11506<System.Object>()#G2_C705::Method0.11497()#G2_C705::Method1.11499()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#G1_C13::Method4.4872()#G1_C13::Method5.4873()#G1_C13::Method6.4875<System.Object>()#G2_C705::Method7.11496<System.Object>()#" call void Generated1268::M.G2_C705.B.B<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C705::Method0.MI.11498()#G2_C705::Method1.MI.11500()#G2_C705::Method2.11501<System.Object>()#G2_C705::Method3.11502<System.Object>()#" call void Generated1268::M.IBase0<class G2_C705`2<class BaseClass1,class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1740`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod4879<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod4878() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod4877() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method1() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method0() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method5() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass0>::Method4() calli default string(class G3_C1740`1<class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass0> on type class G3_C1740`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1740`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod4879<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod4879.17734<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod4878() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod4878.17733()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod4877() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod4877.17732()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::Method7.17731<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2774<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2774.MI.17737<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2773<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2773.MI.17736<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2772() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod2771() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G3_C1740::ClassMethod2771.MI.17735()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method3<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method2<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method1() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method0() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method5() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1740`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1740`1<class BaseClass1>::Method4() calli default string(class G3_C1740`1<class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G3_C1740`1<class BaseClass1> on type class G3_C1740`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass0,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C705`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass0>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C705`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G1_C13`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.MI.4874()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2774<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2774.11506<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2773<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2773.11505<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2772() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2772.11504()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod2771() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::ClassMethod2771.11503()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method1.11499()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method0.11497()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method7.11496<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::ClassMethod1348.4876<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method5.4873()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C705`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C705`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G1_C13::Method4.4872()" ldstr "class G2_C705`2<class BaseClass1,class BaseClass1> on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method0.MI.11498()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method1.MI.11500()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method2.11501<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G2_C705`2<class BaseClass1,class BaseClass1>) ldstr "G2_C705::Method3.11502<System.Object>()" ldstr "IBase0 on type class G2_C705`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated1268::MethodCallingTest() call void Generated1268::ConstrainedCallsTest() call void Generated1268::StructConstrainedInterfaceCallsTest() call void Generated1268::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/native/external/libunwind/src/x86/getcontext-freebsd.S
/* libunwind - a platform-independent unwind library Copyright (C) 2010 Konstantin Belousov <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "offsets.h" .global _Ux86_getcontext .type _Ux86_getcontext, @function _Ux86_getcontext: .cfi_startproc pushl %eax .cfi_adjust_cfa_offset 4 mov 8(%esp),%eax /* ucontext_t* */ popl FREEBSD_UC_MCONTEXT_EAX_OFF(%eax) .cfi_adjust_cfa_offset 4 movl %ebx, FREEBSD_UC_MCONTEXT_EBX_OFF(%eax) movl %ecx, FREEBSD_UC_MCONTEXT_ECX_OFF(%eax) movl %edx, FREEBSD_UC_MCONTEXT_EDX_OFF(%eax) movl %edi, FREEBSD_UC_MCONTEXT_EDI_OFF(%eax) movl %esi, FREEBSD_UC_MCONTEXT_ESI_OFF(%eax) movl %ebp, FREEBSD_UC_MCONTEXT_EBP_OFF(%eax) movl (%esp), %ecx movl %ecx, FREEBSD_UC_MCONTEXT_EIP_OFF(%eax) leal 4(%esp), %ecx /* Exclude the return address. */ movl %ecx, FREEBSD_UC_MCONTEXT_ESP_OFF(%eax) xorl %ecx, %ecx movw %fs, %cx movl %ecx, FREEBSD_UC_MCONTEXT_FS_OFF(%eax) movw %gs, %cx movl %ecx, FREEBSD_UC_MCONTEXT_GS_OFF(%eax) movw %ds, %cx movl %ecx, FREEBSD_UC_MCONTEXT_DS_OFF(%eax) movw %es, %cx movl %ecx, FREEBSD_UC_MCONTEXT_ES_OFF(%eax) movw %ss, %cx movl %ecx, FREEBSD_UC_MCONTEXT_SS_OFF(%eax) movw %cs, %cx movl %ecx, FREEBSD_UC_MCONTEXT_CS_OFF(%eax) pushfl .cfi_adjust_cfa_offset 4 popl FREEBSD_UC_MCONTEXT_EFLAGS_OFF(%eax) .cfi_adjust_cfa_offset -4 movl $0, FREEBSD_UC_MCONTEXT_TRAPNO_OFF(%eax) movl $FREEBSD_UC_MCONTEXT_FPOWNED_FPU,\ FREEBSD_UC_MCONTEXT_OWNEDFP_OFF(%eax) movl $FREEBSD_UC_MCONTEXT_FPFMT_XMM,\ FREEBSD_UC_MCONTEXT_FPFORMAT_OFF(%eax) /* * Require CPU with fxsave implemented, and enabled by OS. * * If passed ucontext is not aligned to 16-byte boundary, * save fpu context into temporary aligned location on stack * and then copy. */ leal FREEBSD_UC_MCONTEXT_FPSTATE_OFF(%eax), %edx testl $0xf, %edx jne 2f fxsave (%edx) /* fast path, passed ucontext save area was aligned */ 1: movl $FREEBSD_UC_MCONTEXT_MC_LEN_VAL,\ FREEBSD_UC_MCONTEXT_MC_LEN_OFF(%eax) xorl %eax, %eax ret 2: movl %edx, %edi /* not aligned, do the dance */ subl $512 + 16, %esp /* save area and 16 bytes for alignment */ .cfi_adjust_cfa_offset 512 + 16 movl %esp, %edx orl $0xf, %edx /* align *%edx to 16-byte up */ incl %edx fxsave (%edx) movl %edx, %esi /* copy to the final destination */ movl $512/4,%ecx rep; movsl addl $512 + 16, %esp /* restore the stack */ .cfi_adjust_cfa_offset -512 - 16 movl FREEBSD_UC_MCONTEXT_ESI_OFF(%eax), %esi movl FREEBSD_UC_MCONTEXT_EDI_OFF(%eax), %edi jmp 1b .cfi_endproc .size _Ux86_getcontext, . - _Ux86_getcontext /* We do not need executable stack. */ .section .note.GNU-stack,"",@progbits
/* libunwind - a platform-independent unwind library Copyright (C) 2010 Konstantin Belousov <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "offsets.h" .global _Ux86_getcontext .type _Ux86_getcontext, @function _Ux86_getcontext: .cfi_startproc pushl %eax .cfi_adjust_cfa_offset 4 mov 8(%esp),%eax /* ucontext_t* */ popl FREEBSD_UC_MCONTEXT_EAX_OFF(%eax) .cfi_adjust_cfa_offset 4 movl %ebx, FREEBSD_UC_MCONTEXT_EBX_OFF(%eax) movl %ecx, FREEBSD_UC_MCONTEXT_ECX_OFF(%eax) movl %edx, FREEBSD_UC_MCONTEXT_EDX_OFF(%eax) movl %edi, FREEBSD_UC_MCONTEXT_EDI_OFF(%eax) movl %esi, FREEBSD_UC_MCONTEXT_ESI_OFF(%eax) movl %ebp, FREEBSD_UC_MCONTEXT_EBP_OFF(%eax) movl (%esp), %ecx movl %ecx, FREEBSD_UC_MCONTEXT_EIP_OFF(%eax) leal 4(%esp), %ecx /* Exclude the return address. */ movl %ecx, FREEBSD_UC_MCONTEXT_ESP_OFF(%eax) xorl %ecx, %ecx movw %fs, %cx movl %ecx, FREEBSD_UC_MCONTEXT_FS_OFF(%eax) movw %gs, %cx movl %ecx, FREEBSD_UC_MCONTEXT_GS_OFF(%eax) movw %ds, %cx movl %ecx, FREEBSD_UC_MCONTEXT_DS_OFF(%eax) movw %es, %cx movl %ecx, FREEBSD_UC_MCONTEXT_ES_OFF(%eax) movw %ss, %cx movl %ecx, FREEBSD_UC_MCONTEXT_SS_OFF(%eax) movw %cs, %cx movl %ecx, FREEBSD_UC_MCONTEXT_CS_OFF(%eax) pushfl .cfi_adjust_cfa_offset 4 popl FREEBSD_UC_MCONTEXT_EFLAGS_OFF(%eax) .cfi_adjust_cfa_offset -4 movl $0, FREEBSD_UC_MCONTEXT_TRAPNO_OFF(%eax) movl $FREEBSD_UC_MCONTEXT_FPOWNED_FPU,\ FREEBSD_UC_MCONTEXT_OWNEDFP_OFF(%eax) movl $FREEBSD_UC_MCONTEXT_FPFMT_XMM,\ FREEBSD_UC_MCONTEXT_FPFORMAT_OFF(%eax) /* * Require CPU with fxsave implemented, and enabled by OS. * * If passed ucontext is not aligned to 16-byte boundary, * save fpu context into temporary aligned location on stack * and then copy. */ leal FREEBSD_UC_MCONTEXT_FPSTATE_OFF(%eax), %edx testl $0xf, %edx jne 2f fxsave (%edx) /* fast path, passed ucontext save area was aligned */ 1: movl $FREEBSD_UC_MCONTEXT_MC_LEN_VAL,\ FREEBSD_UC_MCONTEXT_MC_LEN_OFF(%eax) xorl %eax, %eax ret 2: movl %edx, %edi /* not aligned, do the dance */ subl $512 + 16, %esp /* save area and 16 bytes for alignment */ .cfi_adjust_cfa_offset 512 + 16 movl %esp, %edx orl $0xf, %edx /* align *%edx to 16-byte up */ incl %edx fxsave (%edx) movl %edx, %esi /* copy to the final destination */ movl $512/4,%ecx rep; movsl addl $512 + 16, %esp /* restore the stack */ .cfi_adjust_cfa_offset -512 - 16 movl FREEBSD_UC_MCONTEXT_ESI_OFF(%eax), %esi movl FREEBSD_UC_MCONTEXT_EDI_OFF(%eax), %edi jmp 1b .cfi_endproc .size _Ux86_getcontext, . - _Ux86_getcontext /* We do not need executable stack. */ .section .note.GNU-stack,"",@progbits
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/native/external/libunwind/src/ppc/Linit_remote.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Ginit_remote.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Ginit_remote.c" #endif
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/Generics/Instantiation/Interfaces/class03.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="Class03.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="Class03.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoShortTimePattern.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class DateTimeFormatInfoShortTimePattern { [Fact] public void ShortTimePattern_GetInvariantInfo_ReturnsExpected() { Assert.Equal("HH:mm", DateTimeFormatInfo.InvariantInfo.ShortTimePattern); } public static IEnumerable<object[]> ShortTimePattern_Set_TestData() { yield return new object[] { string.Empty }; yield return new object[] { "garbage" }; yield return new object[] { "dddd, dd MMMM yyyy HH:mm:ss" }; yield return new object[] { "HH:mm" }; yield return new object[] { "t" }; } [Theory] [MemberData(nameof(ShortTimePattern_Set_TestData))] public void ShortTimePattern_Set_GetReturnsExpected(string value) { var format = new DateTimeFormatInfo(); format.ShortTimePattern = value; Assert.Equal(value, format.ShortTimePattern); } [Fact] public void ShortTimePattern_Set_InvalidatesDerivedPattern() { const string Pattern = "#$"; var format = new DateTimeFormatInfo(); var d = DateTimeOffset.Now; d.ToString("g", format); // GeneralShortTimePattern format.ShortTimePattern = Pattern; Assert.Contains(Pattern, d.ToString("g", format)); } [Fact] public void ShortTimePattern_SetNull_ThrowsArgumentNullException() { var format = new DateTimeFormatInfo(); AssertExtensions.Throws<ArgumentNullException>("value", () => format.ShortTimePattern = null); } [Fact] public void ShortTimePattern_SetReadOnly_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => DateTimeFormatInfo.InvariantInfo.ShortTimePattern = "HH:mm"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class DateTimeFormatInfoShortTimePattern { [Fact] public void ShortTimePattern_GetInvariantInfo_ReturnsExpected() { Assert.Equal("HH:mm", DateTimeFormatInfo.InvariantInfo.ShortTimePattern); } public static IEnumerable<object[]> ShortTimePattern_Set_TestData() { yield return new object[] { string.Empty }; yield return new object[] { "garbage" }; yield return new object[] { "dddd, dd MMMM yyyy HH:mm:ss" }; yield return new object[] { "HH:mm" }; yield return new object[] { "t" }; } [Theory] [MemberData(nameof(ShortTimePattern_Set_TestData))] public void ShortTimePattern_Set_GetReturnsExpected(string value) { var format = new DateTimeFormatInfo(); format.ShortTimePattern = value; Assert.Equal(value, format.ShortTimePattern); } [Fact] public void ShortTimePattern_Set_InvalidatesDerivedPattern() { const string Pattern = "#$"; var format = new DateTimeFormatInfo(); var d = DateTimeOffset.Now; d.ToString("g", format); // GeneralShortTimePattern format.ShortTimePattern = Pattern; Assert.Contains(Pattern, d.ToString("g", format)); } [Fact] public void ShortTimePattern_SetNull_ThrowsArgumentNullException() { var format = new DateTimeFormatInfo(); AssertExtensions.Throws<ArgumentNullException>("value", () => format.ShortTimePattern = null); } [Fact] public void ShortTimePattern_SetReadOnly_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => DateTimeFormatInfo.InvariantInfo.ShortTimePattern = "HH:mm"); } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/mono/mono/tests/bug-42136.cs
using System; public class Test { public static int test_0_liveness_exception() { int id = 1; try { id = 2; throw new Exception (); } catch (Exception) { if (id != 2) return id; } return 0; } public static int Main() { int res = 0; res = test_0_liveness_exception (); if (res != 0) Console.WriteLine ("error, test_0_liveness_exception res={0}", res); return 0; } }
using System; public class Test { public static int test_0_liveness_exception() { int id = 1; try { id = 2; throw new Exception (); } catch (Exception) { if (id != 2) return id; } return 0; } public static int Main() { int res = 0; res = test_0_liveness_exception (); if (res != 0) Console.WriteLine ("error, test_0_liveness_exception res={0}", res); return 0; } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/native/libs/System.Security.Cryptography.Native.Apple/pal_keyagree.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_keyagree.h" int32_t AppleCryptoNative_EcdhKeyAgree(SecKeyRef privateKey, SecKeyRef publicKey, CFDataRef* pAgreeOut, CFErrorRef* pErrorOut) { if (pAgreeOut != NULL) *pAgreeOut = NULL; if (pErrorOut != NULL) *pErrorOut = NULL; if (privateKey == NULL || publicKey == NULL) return kErrorBadInput; CFDictionaryRef dict = NULL; *pAgreeOut = SecKeyCopyKeyExchangeResult(privateKey, kSecKeyAlgorithmECDHKeyExchangeStandard, publicKey, dict, pErrorOut); if (*pErrorOut != NULL) return kErrorSeeError; return *pAgreeOut != NULL; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_keyagree.h" int32_t AppleCryptoNative_EcdhKeyAgree(SecKeyRef privateKey, SecKeyRef publicKey, CFDataRef* pAgreeOut, CFErrorRef* pErrorOut) { if (pAgreeOut != NULL) *pAgreeOut = NULL; if (pErrorOut != NULL) *pErrorOut = NULL; if (privateKey == NULL || publicKey == NULL) return kErrorBadInput; CFDictionaryRef dict = NULL; *pAgreeOut = SecKeyCopyKeyExchangeResult(privateKey, kSecKeyAlgorithmECDHKeyExchangeStandard, publicKey, dict, pErrorOut); if (*pErrorOut != NULL) return kErrorSeeError; return *pAgreeOut != NULL; }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/CodeGenBringUpTests/LocallocCnstB5001_PSP_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LocallocCnstB5001_PSP.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LocallocCnstB5001_PSP.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/libraries/System.Private.Uri/src/System/IPv4AddressHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System { // The class designed as to keep minimal the working set of Uri class. // The idea is to stay with static helper methods and strings internal static partial class IPv4AddressHelper { // methods // Parse and canonicalize internal static string ParseCanonicalName(string str, int start, int end, ref bool isLoopback) { unsafe { byte* numbers = stackalloc byte[NumberOfLabels]; isLoopback = Parse(str, numbers, start, end); Span<char> stackSpace = stackalloc char[NumberOfLabels * 3 + 3]; int totalChars = 0, charsWritten; for (int i = 0; i < 3; i++) { numbers[i].TryFormat(stackSpace.Slice(totalChars), out charsWritten); int periodPos = totalChars + charsWritten; stackSpace[periodPos] = '.'; totalChars = periodPos + 1; } numbers[3].TryFormat(stackSpace.Slice(totalChars), out charsWritten); return new string(stackSpace.Slice(0, totalChars + charsWritten)); } } // // Parse // // Convert this IPv4 address into a sequence of 4 8-bit numbers // private static unsafe bool Parse(string name, byte* numbers, int start, int end) { fixed (char* ipString = name) { // end includes ports, so changedEnd may be different from end int changedEnd = end; long result = IPv4AddressHelper.ParseNonCanonical(ipString, start, ref changedEnd, true); Debug.Assert(result != Invalid, $"Failed to parse after already validated: {name}"); unchecked { numbers[0] = (byte)(result >> 24); numbers[1] = (byte)(result >> 16); numbers[2] = (byte)(result >> 8); numbers[3] = (byte)(result); } } return numbers[0] == 127; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System { // The class designed as to keep minimal the working set of Uri class. // The idea is to stay with static helper methods and strings internal static partial class IPv4AddressHelper { // methods // Parse and canonicalize internal static string ParseCanonicalName(string str, int start, int end, ref bool isLoopback) { unsafe { byte* numbers = stackalloc byte[NumberOfLabels]; isLoopback = Parse(str, numbers, start, end); Span<char> stackSpace = stackalloc char[NumberOfLabels * 3 + 3]; int totalChars = 0, charsWritten; for (int i = 0; i < 3; i++) { numbers[i].TryFormat(stackSpace.Slice(totalChars), out charsWritten); int periodPos = totalChars + charsWritten; stackSpace[periodPos] = '.'; totalChars = periodPos + 1; } numbers[3].TryFormat(stackSpace.Slice(totalChars), out charsWritten); return new string(stackSpace.Slice(0, totalChars + charsWritten)); } } // // Parse // // Convert this IPv4 address into a sequence of 4 8-bit numbers // private static unsafe bool Parse(string name, byte* numbers, int start, int end) { fixed (char* ipString = name) { // end includes ports, so changedEnd may be different from end int changedEnd = end; long result = IPv4AddressHelper.ParseNonCanonical(ipString, start, ref changedEnd, true); Debug.Assert(result != Invalid, $"Failed to parse after already validated: {name}"); unchecked { numbers[0] = (byte)(result >> 24); numbers[1] = (byte)(result >> 16); numbers[2] = (byte)(result >> 8); numbers[3] = (byte)(result); } } return numbers[0] == 127; } } }
-1
dotnet/runtime
66,226
[wasm] Add support for symbolicating traces via XHarness
- adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
radical
2022-03-05T00:08:27Z
2022-06-02T01:59:28Z
0f9eb653ef00042c1b8fa1f54e0b388f518c1d59
104013a3be687555af311b60b66491efd2c16f05
[wasm] Add support for symbolicating traces via XHarness. - adds a new `src/mono/wasm/symbolicator` project - which can be used as a standalone command line tool to symbolicate traces manually - has a wrapper that can be passed to xharness, to symbolicate automatically
./src/tests/JIT/Generics/Typeof/valueTypeBoxing.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="valueTypeBoxing.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="valueTypeBoxing.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; // NOTE: The logic in this file is largely a copy of logic in RegexCompiler, emitting C# instead of MSIL. // Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations // are concerned. namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { /// <summary>Code for a [GeneratedCode] attribute to put on the top-level generated members.</summary> private static readonly string s_generatedCodeAttribute = $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(RegexGenerator).Assembly.GetName().Name}\", \"{typeof(RegexGenerator).Assembly.GetName().Version}\")]"; /// <summary>Header comments and usings to include at the top of every generated file.</summary> private static readonly string[] s_headers = new string[] { "// <auto-generated/>", "#nullable enable", "#pragma warning disable CS0162 // Unreachable code", "#pragma warning disable CS0164 // Unreferenced label", "#pragma warning disable CS0219 // Variable assigned but never used", "", }; /// <summary>Generates the code for one regular expression class.</summary> private static (string, ImmutableArray<Diagnostic>) EmitRegexType(RegexType regexClass, bool allowUnsafe) { var sb = new StringBuilder(1024); var writer = new IndentedTextWriter(new StringWriter(sb)); // Emit the namespace if (!string.IsNullOrWhiteSpace(regexClass.Namespace)) { writer.WriteLine($"namespace {regexClass.Namespace}"); writer.WriteLine("{"); writer.Indent++; } // Emit containing types RegexType? parent = regexClass.ParentClass; var parentClasses = new Stack<string>(); while (parent is not null) { parentClasses.Push($"partial {parent.Keyword} {parent.Name}"); parent = parent.ParentClass; } while (parentClasses.Count != 0) { writer.WriteLine($"{parentClasses.Pop()}"); writer.WriteLine("{"); writer.Indent++; } // Emit the direct parent type writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name}"); writer.WriteLine("{"); writer.Indent++; // Generate a name to describe the regex instance. This includes the method name // the user provided and a non-randomized (for determinism) hash of it to try to make // the name that much harder to predict. Debug.Assert(regexClass.Method is not null); string generatedName = $"GeneratedRegex_{regexClass.Method.MethodName}_"; generatedName += ComputeStringHash(generatedName).ToString("X"); // Generate the regex type ImmutableArray<Diagnostic> diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName, allowUnsafe); while (writer.Indent != 0) { writer.Indent--; writer.WriteLine("}"); } writer.Flush(); return (sb.ToString(), diagnostics); // FNV-1a hash function. The actual algorithm used doesn't matter; just something simple // to create a deterministic, pseudo-random value that's based on input text. static uint ComputeStringHash(string s) { uint hashCode = 2166136261; foreach (char c in s) { hashCode = (c ^ hashCode) * 16777619; } return hashCode; } } /// <summary>Gets whether a given regular expression method is supported by the code generator.</summary> private static bool SupportsCodeGeneration(RegexMethod rm, out string? reason) { RegexNode root = rm.Tree.Root; if (!root.SupportsCompilation(out reason)) { return false; } if (ExceedsMaxDepthForSimpleCodeGeneration(root, allowedDepth: 40)) { // Deep RegexNode trees can result in emitting C# code that exceeds C# compiler // limitations, leading to "CS8078: An expression is too long or complex to compile". // Place an artificial limit on max tree depth in order to mitigate such issues. // The allowed depth can be tweaked as needed;its exceedingly rare to find // expressions with such deep trees. reason = "the regex will result in code that may exceed C# compiler limits"; return false; } return true; static bool ExceedsMaxDepthForSimpleCodeGeneration(RegexNode node, int allowedDepth) { if (allowedDepth <= 0) { return true; } int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { if (ExceedsMaxDepthForSimpleCodeGeneration(node.Child(i), allowedDepth - 1)) { return true; } } return false; } } /// <summary>Generates the code for a regular expression method.</summary> private static ImmutableArray<Diagnostic> EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id, bool allowUnsafe) { string patternExpression = Literal(rm.Pattern); string optionsExpression = Literal(rm.Options); string timeoutExpression = rm.MatchTimeout == Timeout.Infinite ? "global::System.Threading.Timeout.InfiniteTimeSpan" : $"global::System.TimeSpan.FromMilliseconds({rm.MatchTimeout.ToString(CultureInfo.InvariantCulture)})"; writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine($"{rm.Modifiers} global::System.Text.RegularExpressions.Regex {rm.MethodName}() => {id}.Instance;"); writer.WriteLine(); writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"); writer.WriteLine($"{(writer.Indent != 0 ? "private" : "internal")} sealed class {id} : global::System.Text.RegularExpressions.Regex"); writer.WriteLine("{"); writer.Write(" public static global::System.Text.RegularExpressions.Regex Instance { get; } = "); // If we can't support custom generation for this regex, spit out a Regex constructor call. if (!SupportsCodeGeneration(rm, out string? reason)) { writer.WriteLine(); writer.WriteLine($"// Cannot generate Regex-derived implementation because {reason}."); writer.WriteLine($"new global::System.Text.RegularExpressions.Regex({patternExpression}, {optionsExpression}, {timeoutExpression});"); writer.WriteLine("}"); return ImmutableArray.Create(Diagnostic.Create(DiagnosticDescriptors.LimitedSourceGeneration, rm.MethodSyntax.GetLocation())); } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(rm.Tree); writer.WriteLine($"new {id}();"); writer.WriteLine(); writer.WriteLine($" private {id}()"); writer.WriteLine($" {{"); writer.WriteLine($" base.pattern = {patternExpression};"); writer.WriteLine($" base.roptions = {optionsExpression};"); writer.WriteLine($" base.internalMatchTimeout = {timeoutExpression};"); writer.WriteLine($" base.factory = new RunnerFactory();"); if (rm.Tree.CaptureNumberSparseMapping is not null) { writer.Write(" base.Caps = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNumberSparseMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNameToNumberMapping is not null) { writer.Write(" base.CapNames = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNameToNumberMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNames is not null) { writer.Write(" base.capslist = new string[] {"); string separator = ""; foreach (string s in rm.Tree.CaptureNames) { writer.Write(separator); writer.Write(Literal(s)); separator = ", "; } writer.WriteLine(" };"); } writer.WriteLine($" base.capsize = {rm.Tree.CaptureCount};"); writer.WriteLine($" }}"); writer.WriteLine(" "); writer.WriteLine($" private sealed class RunnerFactory : global::System.Text.RegularExpressions.RegexRunnerFactory"); writer.WriteLine($" {{"); writer.WriteLine($" protected override global::System.Text.RegularExpressions.RegexRunner CreateInstance() => new Runner();"); writer.WriteLine(); writer.WriteLine($" private sealed class Runner : global::System.Text.RegularExpressions.RegexRunner"); writer.WriteLine($" {{"); // Main implementation methods writer.WriteLine(" // Description:"); DescribeExpression(writer, rm.Tree.Root.Child(0), " // ", analysis); // skip implicit root capture writer.WriteLine(); writer.WriteLine($" protected override void Scan(global::System.ReadOnlySpan<char> text)"); writer.WriteLine($" {{"); writer.Indent += 4; EmitScan(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); writer.WriteLine($" private bool TryFindNextPossibleStartingPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; RequiredHelperFunctions requiredHelpers = EmitTryFindNextPossibleStartingPosition(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); if (allowUnsafe) { writer.WriteLine($" [global::System.Runtime.CompilerServices.SkipLocalsInit]"); } writer.WriteLine($" private bool TryMatchAtCurrentPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; requiredHelpers |= EmitTryMatchAtCurrentPosition(writer, rm, id, analysis); writer.Indent -= 4; writer.WriteLine($" }}"); if ((requiredHelpers & RequiredHelperFunctions.IsWordChar) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character is part of the [\\w] set.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsWordChar(char ch)"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.ReadOnlySpan<byte> ascii = new byte[]"); writer.WriteLine($" {{"); writer.WriteLine($" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,"); writer.WriteLine($" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07"); writer.WriteLine($" }};"); writer.WriteLine(); writer.WriteLine($" int chDiv8 = ch >> 3;"); writer.WriteLine($" return (uint)chDiv8 < (uint)ascii.Length ?"); writer.WriteLine($" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :"); writer.WriteLine($" global::System.Globalization.CharUnicodeInfo.GetUnicodeCategory(ch) switch"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.UppercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.LowercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.TitlecaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ModifierLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.OtherLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.NonSpacingMark or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.DecimalDigitNumber or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ConnectorPunctuation => true,"); writer.WriteLine($" _ => false,"); writer.WriteLine($" }};"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsBoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsBoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsBoundaryWordChar(char ch) =>"); writer.WriteLine($" IsWordChar(ch) || (ch == '\\u200C' | ch == '\\u200D');"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsECMABoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsECMABoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsECMAWordChar(char ch) =>"); writer.WriteLine($" ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter"); writer.WriteLine($" (((uint)ch - '0') < 10) || // digit"); writer.WriteLine($" ch == '_' || // underscore"); writer.WriteLine($" ch == '\\u0130'; // latin capital letter I with dot above"); writer.WriteLine($" }}"); } writer.WriteLine($" }}"); writer.WriteLine($" }}"); writer.WriteLine("}"); return ImmutableArray<Diagnostic>.Empty; static void AppendHashtableContents(IndentedTextWriter writer, Hashtable ht) { IDictionaryEnumerator en = ht.GetEnumerator(); string separator = ""; while (en.MoveNext()) { writer.Write(separator); separator = ", "; writer.Write(" { "); if (en.Key is int key) { writer.Write(key); } else { writer.Write($"\"{en.Key}\""); } writer.Write($", {en.Value} }} "); } } } /// <summary>Emits the body of the Scan method override.</summary> private static void EmitScan(IndentedTextWriter writer, RegexMethod rm, string id) { using (EmitBlock(writer, "while (TryFindNextPossibleStartingPosition(text))")) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("base.CheckTimeout();"); writer.WriteLine(); } writer.WriteLine("// If we find a match on the current position, or we have reached the end of the input, we are done."); using (EmitBlock(writer, "if (TryMatchAtCurrentPosition(text) || base.runtextpos == text.Length)")) { writer.WriteLine("return;"); } writer.WriteLine(); writer.WriteLine("base.runtextpos++;"); } } /// <summary>Emits the body of the TryFindNextPossibleStartingPosition.</summary> private static RequiredHelperFunctions EmitTryFindNextPossibleStartingPosition(IndentedTextWriter writer, RegexMethod rm, string id) { RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; bool hasTextInfo = false; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); // Emit locals initialization writer.WriteLine("int pos = base.runtextpos;"); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; writer.WriteLine(); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = rm.Tree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); string clause = minRequiredLength switch { 0 => "if (pos <= inputSpan.Length)", 1 => "if (pos < inputSpan.Length)", _ => $"if (pos < inputSpan.Length - {minRequiredLength - 1})" }; using (EmitBlock(writer, clause)) { // Emit any anchors. if (!EmitAnchors()) { // Either anchors weren't specified, or they don't completely root all matches to a specific location. // If whatever search operation we need to perform entails case-insensitive operations // that weren't already handled via creation of sets, we need to get an store the // TextInfo object to use (unless RegexOptions.CultureInvariant was specified). EmitTextInfo(writer, ref hasTextInfo, rm); // Emit the code for whatever find mode has been determined. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: writer.WriteLine("return true;"); break; } } } writer.WriteLine(); const string NoStartingPositionFound = "NoStartingPositionFound"; writer.WriteLine("// No starting position found"); writer.WriteLine($"{NoStartingPositionFound}:"); writer.WriteLine("base.runtextpos = inputSpan.Length;"); writer.WriteLine("return false;"); // We're done. Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); return requiredHelpers; // Emit a goto for the specified label. void Goto(string label) => writer.WriteLine($"goto {label};"); // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos > 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: writer.WriteLine("// Start \\G anchor"); using (EmitBlock(writer, "if (pos > base.runtextstart)")) { Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1)")) { writer.WriteLine("base.runtextpos = inputSpan.Length - 1;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { writer.WriteLine("base.runtextpos = inputSpan.Length;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length, minus 1 (for a possible ending \n). writer.WriteLine("// Trailing end \\Z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1};"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: // Jump to the end, minus the min required length, which in this case is actually the fixed length. writer.WriteLine("// Trailing end \\z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength};"); } writer.WriteLine("return true;"); return true; } // Now handle anchors that boost the position but may not determine immediate success or failure. switch (regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. writer.WriteLine("// Beginning-of-line anchor"); using (EmitBlock(writer, "if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');"); using (EmitBlock(writer, "if ((uint)newlinePos > inputSpan.Length - pos - 1)")) { Goto(NoStartingPositionFound); } writer.WriteLine("pos = newlinePos + pos + 1;"); } writer.WriteLine(); break; } switch (regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength};"); } writer.WriteLine(); break; case RegexNodeKind.EndZ when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\Z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength + 1})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength + 1};"); } writer.WriteLine(); break; } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf(string prefix) { writer.WriteLine($"int i = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), {Literal(prefix)});"); writer.WriteLine("if (i >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + i;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; FinishEmitScope loopBlock = default; if (needLoop) { writer.WriteLine("global::System.ReadOnlySpan<char> span = inputSpan.Slice(pos);"); string upperBound = "span.Length" + (setsToUse > 1 || primarySet.Distance != 0 ? $" - {minRequiredLength - 1}" : ""); loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)"); } if (canUseIndexOf) { string span = needLoop ? "span" : "inputSpan.Slice(pos)"; span = (needLoop, primarySet.Distance) switch { (false, 0) => span, (true, 0) => $"{span}.Slice(i)", (false, _) => $"{span}.Slice({primarySet.Distance})", (true, _) => $"{span}.Slice(i + {primarySet.Distance})", }; string indexOf = primarySet.Chars!.Length switch { 1 => $"global::System.MemoryExtensions.IndexOf({span}, {Literal(primarySet.Chars[0])})", 2 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])})", 3 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])}, {Literal(primarySet.Chars[2])})", _ => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(new string(primarySet.Chars))})", }; if (needLoop) { writer.WriteLine($"int indexOfPos = {indexOf};"); using (EmitBlock(writer, "if (indexOfPos < 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("i += indexOfPos;"); writer.WriteLine(); if (setsToUse > 1) { using (EmitBlock(writer, $"if (i >= span.Length - {minRequiredLength - 1})")) { Goto(NoStartingPositionFound); } writer.WriteLine(); } } else { writer.WriteLine($"int i = {indexOf};"); using (EmitBlock(writer, "if (i >= 0)")) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } setIndex = 1; } if (needLoop) { Debug.Assert(setIndex == 0 || setIndex == 1); bool hasCharClassConditions = false; if (setIndex < setsToUse) { // if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") && // ...) Debug.Assert(needLoop); int start = setIndex; for (; setIndex < setsToUse; setIndex++) { string spanIndex = $"span[i{(sets[setIndex].Distance > 0 ? $" + {sets[setIndex].Distance}" : "")}]"; string charInClassExpr = MatchCharacterClass(hasTextInfo, options, spanIndex, sets[setIndex].Set, sets[setIndex].CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers); if (setIndex == start) { writer.Write($"if ({charInClassExpr}"); } else { writer.WriteLine(" &&"); writer.Write($" {charInClassExpr}"); } } writer.WriteLine(")"); hasCharClassConditions = true; } using (hasCharClassConditions ? EmitBlock(writer, null) : default) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } loopBlock.Dispose(); } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); using (EmitBlock(writer, "while (true)")) { writer.WriteLine($"global::System.ReadOnlySpan<char> slice = inputSpan.Slice(pos);"); writer.WriteLine(); // Find the literal. If we can't find it, we're done searching. writer.Write("int i = global::System.MemoryExtensions."); writer.WriteLine( target.Literal.String is string literalString ? $"IndexOf(slice, {Literal(literalString)});" : target.Literal.Chars is not char[] literalChars ? $"IndexOf(slice, {Literal(target.Literal.Char)});" : literalChars.Length switch { 2 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])});", 3 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])}, {Literal(literalChars[2])});", _ => $"IndexOfAny(slice, {Literal(new string(literalChars))});", }); using (EmitBlock(writer, $"if (i < 0)")) { writer.WriteLine("break;"); } writer.WriteLine(); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. writer.WriteLine("int prev = i;"); writer.WriteLine($"while ((uint)--prev < (uint)slice.Length && {MatchCharacterClass(hasTextInfo, options, "slice[prev]", target.LoopNode.Str!, caseInsensitive: false, negate: false, additionalDeclarations, ref requiredHelpers)});"); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. writer.WriteLine($"if ((i - prev - 1) < {target.LoopNode.M})"); writer.WriteLine("{"); writer.WriteLine(" pos += i + 1;"); writer.WriteLine(" continue;"); writer.WriteLine("}"); } writer.WriteLine(); // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. writer.WriteLine("base.runtextpos = pos + prev + 1;"); writer.WriteLine("return true;"); } } // If a TextInfo is needed to perform ToLower operations, emits a local initialized to the TextInfo to use. static void EmitTextInfo(IndentedTextWriter writer, ref bool hasTextInfo, RegexMethod rm) { // Emit local to store current culture if needed if ((rm.Options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = rm.Tree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when rm.Tree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { hasTextInfo = true; writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); } } } } /// <summary>Emits the body of the TryMatchAtCurrentPosition.</summary> private static RequiredHelperFunctions EmitTryMatchAtCurrentPosition(IndentedTextWriter writer, RegexMethod rm, string id, AnalysisResults analysis) { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // Helper to define names. Names start unadorned, but as soon as there's repetition, // they begin to have a numbered suffix. var usedNames = new Dictionary<string, int>(); // Every RegexTree is rooted in the implicit Capture for the whole expression. // Skip the Capture node. We handle the implicit root capture specially. RegexNode node = regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. writer.WriteLine($"int start = base.runtextpos;"); writer.WriteLine($"int end = start + {(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1)};"); writer.WriteLine("base.Capture(0, start, end);"); writer.WriteLine("base.runtextpos = end;"); writer.WriteLine("return true;"); return requiredHelpers; case RegexNodeKind.Empty: // This case isn't common in production, but it's very common when first getting started with the // source generator and seeing what happens as you add more to expressions. When approaching // it from a learning perspective, this is very common, as it's the empty string you start with. writer.WriteLine("base.Capture(0, base.runtextpos, base.runtextpos);"); writer.WriteLine("return true;"); return requiredHelpers; } // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); var additionalLocalFunctions = new Dictionary<string, string[]>(); // Declare some locals. string sliceSpan = "slice"; writer.WriteLine("int pos = base.runtextpos;"); writer.WriteLine($"int original_pos = pos;"); bool hasTimeout = EmitLoopTimeoutCounterIfNeeded(writer, rm); bool hasTextInfo = EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(writer, rm, analysis); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(writer, defineLocal: true); writer.WriteLine(); // doneLabel starts out as the top-level label for the whole expression failing to match. However, // it may be changed by the processing of a node to point to whereever subsequent match failures // should jump to, in support of backtracking or other constructs. For example, before emitting // the code for a branch N, an alternation will set the the doneLabel to point to the label for // processing the next branch N+1: that way, any failures in the branch N's processing will // implicitly end up jumping to the right location without needing to know in what context it's used. string doneLabel = ReserveName("NoMatch"); string topLevelDoneLabel = doneLabel; // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // If we fall through to this place in the code, we've successfully matched the expression. writer.WriteLine(); writer.WriteLine("// The input matched."); if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); // TransferSliceStaticPosToPos would also slice, which isn't needed here } writer.WriteLine("base.runtextpos = pos;"); writer.WriteLine("base.Capture(0, original_pos, pos);"); writer.WriteLine("return true;"); // We're done with the match. // Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); // And emit any required helpers. if (additionalLocalFunctions.Count != 0) { foreach (KeyValuePair<string, string[]> localFunctions in additionalLocalFunctions.OrderBy(k => k.Key)) { writer.WriteLine(); foreach (string line in localFunctions.Value) { writer.WriteLine(line); } } } return requiredHelpers; // Helper to create a name guaranteed to be unique within the function. string ReserveName(string prefix) { usedNames.TryGetValue(prefix, out int count); usedNames[prefix] = count + 1; return count == 0 ? prefix : $"{prefix}{count}"; } // Helper to emit a label. As of C# 10, labels aren't statements of their own and need to adorn a following statement; // if a label appears just before a closing brace, then, it's a compilation error. To avoid issues there, this by // default implements a blank statement (a semicolon) after each label, but individual uses can opt-out of the semicolon // when it's known the label will always be followed by a statement. void MarkLabel(string label, bool emitSemicolon = true) => writer.WriteLine($"{label}:{(emitSemicolon ? ";" : "")}"); // Emits a goto to jump to the specified label. However, if the specified label is the top-level done label indicating // that the entire match has failed, we instead emit our epilogue, uncapturing if necessary and returning out of TryMatchAtCurrentPosition. void Goto(string label) { if (label == topLevelDoneLabel) { // We only get here in the code if the whole expression fails to match and jumps to // the original value of doneLabel. if (expressionHasCaptures) { EmitUncaptureUntil("0"); } writer.WriteLine("return false; // The input didn't match."); } else { writer.WriteLine($"goto {label};"); } } // Emits a case or default line followed by an indented body. void CaseGoto(string clause, string label) { writer.WriteLine(clause); writer.Indent++; Goto(label); writer.Indent--; } // Whether the node has RegexOptions.IgnoreCase set. static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan(IndentedTextWriter writer, bool defineLocal = false) { if (defineLocal) { writer.Write("global::System.ReadOnlySpan<char> "); } writer.WriteLine($"{sliceSpan} = inputSpan.Slice(pos);"); } // Emits the sum of a constant and a value from a local. string Sum(int constant, string? local = null) => local is null ? constant.ToString(CultureInfo.InvariantCulture) : constant == 0 ? local : $"{constant} + {local}"; // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) { Debug.Assert(requiredLength > 0); using (EmitBlock(writer, $"if ({SpanLengthCheck(requiredLength, dynamicRequiredLength)})")) { Goto(doneLabel); } } // Returns a length check for the current span slice. The check returns true if // the span isn't long enough for the specified length. string SpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) => dynamicRequiredLength is null && sliceStaticPos + requiredLength == 1 ? $"{sliceSpan}.IsEmpty" : $"(uint){sliceSpan}.Length < {Sum(sliceStaticPos + requiredLength, dynamicRequiredLength)}"; // Adds the value of sliceStaticPos into the pos local, slices slice by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos() { if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({sliceStaticPos});"); sliceStaticPos = 0; } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); string originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // If no child branch overlaps with another child branch, we can emit more streamlined code // that avoids checking unnecessary branches, e.g. with abc|def|ghi if the next character in // the input is 'a', we needn't try the def or ghi branches. A simple, relatively common case // of this is if every branch begins with a specific, unique character, in which case // the whole alternation can be treated as a simple switch, so we special-case that. However, // we can't goto _into_ switch cases, which means we can't use this approach if there's any // possibility of backtracking into the alternation. bool useSwitchedBranches = isAtomic; if (!useSwitchedBranches) { useSwitchedBranches = true; for (int i = 0; i < childCount; i++) { if (analysis.MayBacktrack(node.Child(i))) { useSwitchedBranches = false; break; } } } // Detect whether every branch begins with one or more unique characters. const int SetCharsSize = 5; // arbitrary limit (for IgnoreCase, we want this to be at least 3 to handle the vast majority of values) Span<char> setChars = stackalloc char[SetCharsSize]; if (useSwitchedBranches) { // Iterate through every branch, seeing if we can easily find a starting One, Multi, or small Set. // If we can, extract its starting char (or multiple in the case of a set), validate that all such // starting characters are unique relative to all the branches. var seenChars = new HashSet<char>(); for (int i = 0; i < childCount && useSwitchedBranches; i++) { // If it's not a One, Multi, or Set, we can't apply this optimization. // If it's IgnoreCase (and wasn't reduced to a non-IgnoreCase set), also ignore it to keep the logic simple. if (node.Child(i).FindBranchOneMultiOrSetStart() is not RegexNode oneMultiOrSet || (oneMultiOrSet.Options & RegexOptions.IgnoreCase) != 0) // TODO: https://github.com/dotnet/runtime/issues/61048 { useSwitchedBranches = false; break; } // If it's a One or a Multi, get the first character and add it to the set. // If it was already in the set, we can't apply this optimization. if (oneMultiOrSet.Kind is RegexNodeKind.One or RegexNodeKind.Multi) { if (!seenChars.Add(oneMultiOrSet.FirstCharOfOneOrMulti())) { useSwitchedBranches = false; break; } } else { // The branch begins with a set. Make sure it's a set of only a few characters // and get them. If we can't, we can't apply this optimization. Debug.Assert(oneMultiOrSet.Kind is RegexNodeKind.Set); int numChars; if (RegexCharClass.IsNegated(oneMultiOrSet.Str!) || (numChars = RegexCharClass.GetSetChars(oneMultiOrSet.Str!, setChars)) == 0) { useSwitchedBranches = false; break; } // Check to make sure each of the chars is unique relative to all other branches examined. foreach (char c in setChars.Slice(0, numChars)) { if (!seenChars.Add(c)) { useSwitchedBranches = false; break; } } } } } if (useSwitchedBranches) { // Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the // C# compiler to lower the C# switch statement with appropriate optimizations. In some // cases there are enough branches that the compiler will emit a jump table. In others // it'll optimize the order of checks in order to minimize the total number in the worst // case. In any case, we get easier to read and reason about C#. EmitSwitchedBranches(); } else { EmitAllBranches(); } return; // Emits the code for a switch-based alternation of non-overlapping branches. void EmitSwitchedBranches() { // We need at least 1 remaining character in the span, for the char to switch on. EmitSpanLengthCheck(1); writer.WriteLine(); // Emit a switch statement on the first char of each branch. using (EmitBlock(writer, $"switch ({sliceSpan}[{sliceStaticPos++}])")) { Span<char> setChars = stackalloc char[SetCharsSize]; // needs to be same size as detection check in caller int startingSliceStaticPos = sliceStaticPos; // Emit a case for each branch. for (int i = 0; i < childCount; i++) { sliceStaticPos = startingSliceStaticPos; RegexNode child = node.Child(i); Debug.Assert(child.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set or RegexNodeKind.Concatenate, DescribeNode(child, analysis)); Debug.Assert(child.Kind is not RegexNodeKind.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set)); RegexNode? childStart = child.FindBranchOneMultiOrSetStart(); Debug.Assert(childStart is not null, "Unexpectedly couldn't find the branch starting node."); Debug.Assert((childStart.Options & RegexOptions.IgnoreCase) == 0, "Expected only to find non-IgnoreCase branch starts"); if (childStart.Kind is RegexNodeKind.Set) { int numChars = RegexCharClass.GetSetChars(childStart.Str!, setChars); Debug.Assert(numChars != 0); writer.WriteLine($"case {string.Join(" or ", setChars.Slice(0, numChars).ToArray().Select(c => Literal(c)))}:"); } else { writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); } writer.Indent++; // Emit the code for the branch, without the first character that was already matched in the switch. switch (child.Kind) { case RegexNodeKind.Multi: EmitNode(CloneMultiWithoutFirstChar(child)); writer.WriteLine(); break; case RegexNodeKind.Concatenate: var newConcat = new RegexNode(RegexNodeKind.Concatenate, child.Options); if (childStart.Kind == RegexNodeKind.Multi) { newConcat.AddChild(CloneMultiWithoutFirstChar(childStart)); } int concatChildCount = child.ChildCount(); for (int j = 1; j < concatChildCount; j++) { newConcat.AddChild(child.Child(j)); } EmitNode(newConcat.Reduce()); writer.WriteLine(); break; static RegexNode CloneMultiWithoutFirstChar(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Multi); Debug.Assert(node.Str!.Length >= 2); return node.Str!.Length == 2 ? new RegexNode(RegexNodeKind.One, node.Options, node.Str![1]) : new RegexNode(RegexNodeKind.Multi, node.Options, node.Str!.Substring(1)); } } // This is only ever used for atomic alternations, so we can simply reset the doneLabel // after emitting the child, as nothing will backtrack here (and we need to reset it // so that all branches see the original). doneLabel = originalDoneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); writer.WriteLine($"break;"); writer.WriteLine(); writer.Indent--; } // Default branch if the character didn't match the start of any branches. CaseGoto("default:", doneLabel); } } void EmitAllBranches() { // Label to jump to when any branch completes successfully. string matchLabel = ReserveName("AlternationMatch"); // Save off pos. We'll need to reset this each time a branch fails. string startingPos = ReserveName("alternation_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. string? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { startingCapturePos = ReserveName("alternation_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } writer.WriteLine(); // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new string[childCount]; string backtrackLabel = ReserveName("AlternationBacktrack"); for (int i = 0; i < childCount; i++) { // If the alternation isn't atomic, backtracking may require our jump table jumping back // into these branches, so we can't use actual scopes, as that would hide the labels. using (EmitScope(writer, $"Branch {i}", faux: !isAtomic)) { bool isLastBranch = i == childCount - 1; string? nextBranch = null; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = ReserveName("AlternationBranch"); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); writer.WriteLine(); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { EmitStackPush(startingCapturePos is not null ? new[] { i.ToString(), startingPos, startingCapturePos } : new[] { i.ToString(), startingPos }); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); if (!isLastBranch || !isAtomic) { // If this isn't the last branch, we're about to output a reset section, // and if this isn't atomic, there will be a backtracking section before // the end of the method. In both of those cases, we've successfully // matched and need to skip over that code. If, however, this is the // last branch and this is an atomic alternation, we can just fall // through to the successfully matched location. Goto(matchLabel); } // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { writer.WriteLine(); MarkLabel(nextBranch!, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } writer.WriteLine(); } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel, emitSemicolon: false); EmitStackPop(startingCapturePos is not null ? new[] { startingCapturePos, startingPos } : new[] { startingPos}); using (EmitBlock(writer, $"switch ({StackPop()})")) { for (int i = 0; i < labelMap.Length; i++) { CaseGoto($"case {i}:", labelMap[i]); } } writer.WriteLine(); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); if (sliceStaticPos > 0) { TransferSliceStaticPosToPos(); writer.WriteLine(); } // If the specified capture hasn't yet captured anything, fail to match... except when using RegexOptions.ECMAScript, // in which case per ECMA 262 section 21.2.2.9 the backreference should succeed. if ((node.Options & RegexOptions.ECMAScript) != 0) { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { EmitWhenHasCapture(); } } else { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference doesn't match."); using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(doneLabel); } writer.WriteLine(); EmitWhenHasCapture(); } void EmitWhenHasCapture() { writer.WriteLine("// Get the captured text. If it doesn't match at the current position, the backreference doesn't match."); additionalDeclarations.Add("int matchLength = 0;"); writer.WriteLine($"matchLength = base.MatchLength({capnum});"); if (!IsCaseInsensitive(node)) { // If we're case-sensitive, we can simply validate that the remaining length of the slice is sufficient // to possibly match, and then do a SequenceEqual against the matched text. writer.WriteLine($"if ({sliceSpan}.Length < matchLength || "); using (EmitBlock(writer, $" !global::System.MemoryExtensions.SequenceEqual(inputSpan.Slice(base.MatchIndex({capnum}), matchLength), {sliceSpan}.Slice(0, matchLength)))")) { Goto(doneLabel); } } else { // For case-insensitive, we have to walk each character individually. using (EmitBlock(writer, $"if ({sliceSpan}.Length < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"inputSpan[matchIndex + i]")} != {ToLower(hasTextInfo, options, $"{sliceSpan}[i]")})")) { Goto(doneLabel); } } } writer.WriteLine(); writer.WriteLine($"pos += matchLength;"); SliceInputSpan(writer); } } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; // If the child branches might backtrack, we can't emit the branches inside constructs that // require braces, e.g. if/else, even though that would yield more idiomatic output. // But if we know for certain they won't backtrack, we can output the nicer code. if (analysis.IsAtomicByAncestor(node) || (!analysis.MayBacktrack(yesBranch) && (noBranch is null || !analysis.MayBacktrack(noBranch)))) { using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { writer.WriteLine($"// The {DescribeCapture(node.M, analysis)} captured a value. Match the first branch."); EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } if (noBranch is not null) { using (EmitBlock(writer, $"else")) { writer.WriteLine($"// Otherwise, match the second branch."); EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } } doneLabel = originalDoneLabel; // atomicity return; } string refNotMatched = ReserveName("ConditionalBackreferenceNotMatched"); string endConditional = ReserveName("ConditionalBackreferenceEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalbackreference_branch"); writer.WriteLine($"int {resumeAt} = 0;"); // While it would be nicely readable to use an if/else block, if the branches contain // anything that triggers backtracking, labels will end up being defined, and if they're // inside the scope block for the if or else, that will prevent jumping to them from // elsewhere. So we implement the if/else with labels and gotos manually. // Check to see if the specified capture number was captured. using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(refNotMatched); } writer.WriteLine(); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { Goto(endConditional); writer.WriteLine(); } MarkLabel(refNotMatched); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. bool hasBacktracking = postYesDoneLabel != originalDoneLabel || postNoDoneLabel != originalDoneLabel; if (hasBacktracking) { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); // Backtrack section string backtrack = ReserveName("ConditionalBackreferenceBacktrack"); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } } if (needsEndConditional) { MarkLabel(endConditional); } if (hasBacktracking) { // We're not atomic and at least one of the yes or no branches contained backtracking constructs, // so finish outputting our backtracking logic, which involves pushing onto the stack which // branch to backtrack into. EmitStackPush(resumeAt); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookahead. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; string expressionNotMatched = ReserveName("ConditionalExpressionNotMatched"); string endConditional = ReserveName("ConditionalExpressionEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalexpression_branch"); if (!isAtomic) { writer.WriteLine($"int {resumeAt} = 0;"); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. string? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { startingCapturePos = ReserveName("conditionalexpression_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookahead; however, a positive lookahead only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("conditionalexpression_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. writer.WriteLine("// Condition:"); EmitNode(condition); writer.WriteLine(); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. writer.WriteLine("// Condition matched:"); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; writer.WriteLine(); // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } Goto(endConditional); writer.WriteLine(); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. writer.WriteLine("// Condition did not match:"); MarkLabel(expressionNotMatched, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } writer.WriteLine(); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); string backtrack = ReserveName("ConditionalExpressionBacktrack"); doneLabel = backtrack; MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } MarkLabel(endConditional, emitSemicolon: false); EmitStackPush(resumeAt); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, rm.Tree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); TransferSliceStaticPosToPos(); string startingPos = ReserveName("capture_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); RegexNode child = node.Child(0); if (uncapnum != -1) { using (EmitBlock(writer, $"if (!base.IsMatched({uncapnum}))")) { Goto(doneLabel); } writer.WriteLine(); } // Emit child node. string originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; writer.WriteLine(); TransferSliceStaticPosToPos(); if (uncapnum == -1) { writer.WriteLine($"base.Capture({capnum}, {startingPos}, pos);"); } else { writer.WriteLine($"base.TransferCapture({capnum}, {uncapnum}, {startingPos}, pos);"); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. writer.WriteLine(); EmitStackPush(startingPos); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"CaptureBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(startingPos); if (!childBacktracks) { writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } // Emits the code to handle a positive lookahead assertion. void EmitPositiveLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("positivelookahead_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. writer.WriteLine(); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; } // Emits the code to handle a negative lookahead assertion. void EmitNegativeLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); string originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("negativelookahead_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; string negativeLookaheadDoneLabel = ReserveName("NegativeLookaheadMatch"); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookahead, which actually // means failure for a _negative_ lookahead, so we need to jump to the original done. writer.WriteLine(); Goto(originalDoneLabel); writer.WriteLine(); // Failures (success for a negative lookahead) jump here. MarkLabel(negativeLookaheadDoneLabel, emitSemicolon: false); // After the child completes in failure (success for negative lookahead), reset the text positions. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } // Separate out several node types that, for conciseness, don't need a header and scope written into the source. switch (node.Kind) { // Nothing is written for an empty case RegexNodeKind.Empty: return; // A match failure doesn't need a scope. case RegexNodeKind.Nothing: Goto(doneLabel); return; // Skip atomic nodes that wrap non-backtracking children; in such a case there's nothing to be made atomic. case RegexNodeKind.Atomic when !analysis.MayBacktrack(node.Child(0)): EmitNode(node.Child(0)); return; // Concatenate is a simplification in the node tree so that a series of children can be represented as one. // We don't need its presence visible in the source. case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); return; } // Put the node's code into its own scope. If the node contains labels that may need to // be visible outside of its scope, the scope is still emitted for clarity but is commented out. using (EmitScope(writer, DescribeNode(node, analysis), faux: analysis.MayBacktrack(node))) { switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Atomic when analysis.MayBacktrack(node.Child(0)): EmitAtomic(node, subsequent); return; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaheadAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaheadAssertion(node); break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(analysis.MayBacktrack(node.Child(0)), "Expected child to potentially backtrack"); // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. string originalDoneLabel = doneLabel; additionalDeclarations.Add("int stackpos = 0;"); string startingStackpos = ReserveName("atomic_stackpos"); writer.WriteLine($"int {startingStackpos} = stackpos;"); writer.WriteLine(); // Emit the child. EmitNode(node.Child(0), subsequent); writer.WriteLine(); // Reset the stack position and done label. writer.WriteLine($"stackpos = {startingStackpos};"); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); TransferSliceStaticPosToPos(); using (EmitBlock(writer, "if (base.runtextpos < pos)")) { writer.WriteLine("base.runtextpos = pos;"); } } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. string? prevDescription = null; int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. We also want to minimize the repetition of if blocks, // and so we try to emit a series of clauses all part of the same if block rather than one if block per child. if (emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { bool wroteClauses = true; writer.Write($"if ({SpanLengthCheck(requiredLength)}"); while (i < exclusiveEnd) { for (; i < exclusiveEnd; i++) { void WriteSingleCharChild(RegexNode child, bool includeDescription = true) { if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $" || // {prevDescription}" : " ||"); writer.Write(" "); } else { writer.Write("if ("); } EmitSingleChar(child, emitLengthCheck: false, clauseOnly: true); prevDescription = includeDescription ? DescribeNode(child, analysis) : null; wroteClauses = true; } RegexNode child = node.Child(i); if (child.Kind is RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set) { WriteSingleCharChild(child); } else if (child.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic && child.M == child.N && child.M <= MaxUnrollSize) { for (int c = 0; c < child.M; c++) { WriteSingleCharChild(child, includeDescription: c == 0); } } else { break; } } if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $") // {prevDescription}" : ")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } if (i < childCount) { writer.WriteLine(); } wroteClauses = false; prevDescription = null; } if (i < exclusiveEnd) { EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: false); if (i < childCount - 1) { writer.WriteLine(); } i++; } } i--; continue; } EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: emitLengthChecksIfRequired); if (i < childCount - 1) { writer.WriteLine(); } } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequentOrDefault(int index, RegexNode node, RegexNode? defaultNode) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return defaultNode; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, string? offset = null, bool clauseOnly = false) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); // This only emits a single check, but it's called from the looping constructs in a loop // to generate the code for a single check, so we map those looping constructs to the // appropriate single check. string expr = $"{sliceSpan}[{Sum(sliceStaticPos, offset)}]"; if (node.IsSetFamily) { expr = $"{MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: true, additionalDeclarations, ref requiredHelpers)}"; } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "!=" : "==")} {Literal(node.Ch)}"; } if (clauseOnly) { writer.Write(expr); } else { using (EmitBlock(writer, emitLengthCheck ? $"if ({SpanLengthCheck(1, offset)} || {expr})" : $"if ({expr})")) { Goto(doneLabel); } } sliceStaticPos++; } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); string call = node.Kind switch { RegexNodeKind.Boundary => "!IsBoundary", RegexNodeKind.NonBoundary => "IsBoundary", RegexNodeKind.ECMABoundary => "!IsECMABoundary", _ => "IsECMABoundary", }; RequiredHelperFunctions boundaryFunctionRequired = node.Kind switch { RegexNodeKind.Boundary or RegexNodeKind.NonBoundary => RequiredHelperFunctions.IsBoundary | RequiredHelperFunctions.IsWordChar, // IsBoundary internally uses IsWordChar _ => RequiredHelperFunctions.IsECMABoundary }; requiredHelpers |= boundaryFunctionRequired; using (EmitBlock(writer, $"if ({call}(inputSpan, pos{(sliceStaticPos > 0 ? $" + {sliceStaticPos}" : "")}))")) { Goto(doneLabel); } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. Goto(doneLabel); } else { using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != 0)" : "if (pos != base.runtextstart)")) { Goto(doneLabel); } } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { using (EmitBlock(writer, $"if ({sliceSpan}[{sliceStaticPos - 1}] != '\\n')")) { Goto(doneLabel); } } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the inputSpan field directly: using (EmitBlock(writer, $"if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { Goto(doneLabel); } } break; case RegexNodeKind.End: using (EmitBlock(writer, $"if ({IsSliceLengthGreaterThanSliceStaticPos()})")) { Goto(doneLabel); } break; case RegexNodeKind.EndZ: writer.WriteLine($"if ({sliceSpan}.Length > {sliceStaticPos + 1} || ({IsSliceLengthGreaterThanSliceStaticPos()} && {sliceSpan}[{sliceStaticPos}] != '\\n'))"); using (EmitBlock(writer, null)) { Goto(doneLabel); } break; case RegexNodeKind.Eol: using (EmitBlock(writer, $"if ({IsSliceLengthGreaterThanSliceStaticPos()} && {sliceSpan}[{sliceStaticPos}] != '\\n')")) { Goto(doneLabel); } break; string IsSliceLengthGreaterThanSliceStaticPos() => sliceStaticPos == 0 ? $"!{sliceSpan}.IsEmpty" : $"{sliceSpan}.Length > {sliceStaticPos}"; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); Debug.Assert(node.Str is not null); EmitMultiCharString(node.Str, IsCaseInsensitive(node), emitLengthCheck); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck) { Debug.Assert(str.Length >= 2); if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } using (EmitBlock(writer, $"for (int i = 0; i < {Literal(str)}.Length; i++)")) { string textSpanIndex = sliceStaticPos > 0 ? $"i + {sliceStaticPos}" : "i"; using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"{sliceSpan}[{textSpanIndex}]")} != {Literal(str)}[i])")) { Goto(doneLabel); } } } else { string sourceSpan = sliceStaticPos > 0 ? $"{sliceSpan}.Slice({sliceStaticPos})" : sliceSpan; using (EmitBlock(writer, $"if (!global::System.MemoryExtensions.StartsWith({sourceSpan}, {Literal(str)}))")) { Goto(doneLabel); } } sliceStaticPos += str.Length; } void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); string backtrackingLabel = ReserveName("CharLoopBacktrack"); string endLoop = ReserveName("CharLoopEnd"); string startingPos = ReserveName("charloop_starting_pos"); string endingPos = ReserveName("charloop_ending_pos"); additionalDeclarations.Add($"int {startingPos} = 0, {endingPos} = 0;"); // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); EmitSingleCharAtomicLoop(node); writer.WriteLine(); TransferSliceStaticPosToPos(); writer.WriteLine($"{endingPos} = pos;"); EmitAdd(writer, startingPos, node.M); Goto(endLoop); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel, emitSemicolon: false); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } EmitStackPop(endingPos, startingPos); writer.WriteLine(); if (subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { writer.WriteLine($"if ({startingPos} >= {endingPos} ||"); using (EmitBlock(writer, literal.Item2 is not null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, global::System.Math.Min(inputSpan.Length, {endingPos} + {literal.Item2.Length - 1}) - {startingPos}), {Literal(literal.Item2)})) < 0)" : literal.Item3 is null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item1)})) < 0)" : literal.Item3.Length switch { 2 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])})) < 0)", 3 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])}, {Literal(literal.Item3[2])})) < 0)", _ => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3)})) < 0)", })) { Goto(doneLabel); } writer.WriteLine($"{endingPos} += {startingPos};"); writer.WriteLine($"pos = {endingPos};"); } else { using (EmitBlock(writer, $"if ({startingPos} >= {endingPos})")) { Goto(doneLabel); } writer.WriteLine($"pos = --{endingPos};"); } SliceInputSpan(writer); writer.WriteLine(); MarkLabel(endLoop, emitSemicolon: false); EmitStackPush(expressionHasCaptures ? new[] { startingPos, endingPos, "base.Crawlpos()" } : new[] { startingPos, endingPos }); doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } if (node.M > 0) { // We emitted a repeater to handle the required iterations; add a newline after it. writer.WriteLine(); } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. string? iterationCount = null; string? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = $"{node.N - node.M}"; iterationCount = ReserveName("lazyloop_iteration"); writer.WriteLine($"int {iterationCount} = 0;"); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. string? capturePos = null; if (expressionHasCaptures) { capturePos = ReserveName("lazyloop_capturepos"); additionalDeclarations.Add($"int {capturePos} = 0;"); } // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. string startingPos = ReserveName("lazyloop_pos"); additionalDeclarations.Add($"int {startingPos} = 0;"); writer.WriteLine($"{startingPos} = pos;"); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. string endLoopLabel = ReserveName("LazyLoopEnd"); Goto(endLoopLabel); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here. string backtrackingLabel = ReserveName("LazyLoopBacktrack"); MarkLabel(backtrackingLabel, emitSemicolon: false); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturePos is not null) { EmitUncaptureUntil(capturePos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { using (EmitBlock(writer, $"if ({iterationCount} >= {maxIterations})")) { Goto(doneLabel); } writer.WriteLine($"{iterationCount}++;"); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). writer.WriteLine( literal.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item2[0])});" : literal.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item1)});" : literal.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch + literal.Item3)});", }); using (EmitBlock(writer, $"if ((uint){startingPos} >= (uint){sliceSpan}.Length || {sliceSpan}[{startingPos}] == {Literal(node.Ch)})")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. writer.WriteLine( literal2.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item2)});" : literal2.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item1)});" : literal2.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])});", 3 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])}, {Literal(literal2.Item3[2])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3)});", }); using (EmitBlock(writer, $"if ({startingPos} < 0)")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } // Store the position we've left off at in case we need to iterate again. writer.WriteLine($"{startingPos} = pos;"); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. string originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes writer.WriteLine(); MarkLabel(endLoopLabel); if (capturePos is not null) { writer.WriteLine($"{capturePos} = base.Crawlpos();"); } if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state var toPushPop = new List<string>(3) { startingPos }; if (capturePos is not null) { toPushPop.Add(capturePos); } if (iterationCount is not null) { toPushPop.Add(iterationCount); } string[] toPushPopArray = toPushPop.ToArray(); EmitStackPush(toPushPopArray); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("CharLazyBacktrack"); MarkLabel(backtrack, emitSemicolon: false); Array.Reverse(toPushPopArray); EmitStackPop(toPushPopArray); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; string originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } writer.WriteLine(); } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string startingPos = ReserveName("lazyloop_starting_pos"); string iterationCount = ReserveName("lazyloop_iteration"); string sawEmpty = ReserveName("lazyLoopEmptySeen"); string body = ReserveName("LazyLoopBody"); string endLoop = ReserveName("LazyLoopEnd"); writer.WriteLine($"int {iterationCount} = 0, {startingPos} = pos, {sawEmpty} = 0;"); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { Goto(endLoop); } writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos", sawEmpty } : new[] { startingPos, "pos", sawEmpty }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LazyLoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(body); } } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. using (EmitBlock(writer, $"if (pos == {startingPos})")) { writer.WriteLine($"{sawEmpty} = 1;"); } // We matched the next iteration. Jump to the subsequent code. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop(sawEmpty, "pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (doneLabel == originalDoneLabel) { Goto(originalDoneLabel); } else { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); } writer.WriteLine(); MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackPush(startingPos, iterationCount, sawEmpty); string skipBacktrack = ReserveName("SkipBacktrack"); Goto(skipBacktrack); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"LazyLoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(sawEmpty, iterationCount, startingPos); if (maxIterations == int.MaxValue) { using (EmitBlock(writer, $"if ({sawEmpty} == 0)")) { Goto(body); } } else { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, maxIterations)} && {sawEmpty} == 0)")) { Goto(body); } } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthCheck = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthCheck); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthCheck); return; } if (iterations <= MaxUnrollSize) { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length || // slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // { // goto doneLabel; // } writer.Write($"if ("); if (emitLengthCheck) { writer.WriteLine($"{SpanLengthCheck(iterations)} ||"); writer.Write(" "); } EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); for (int i = 1; i < iterations; i++) { writer.WriteLine(" ||"); writer.Write(" "); EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); } writer.WriteLine(")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } } else { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthCheck) { EmitSpanLengthCheck(iterations); } string repeaterSpan = "repeaterSlice"; // As this repeater doesn't wrap arbitrary node emits, this shouldn't conflict with anything writer.WriteLine($"global::System.ReadOnlySpan<char> {repeaterSpan} = {sliceSpan}.Slice({sliceStaticPos}, {iterations});"); using (EmitBlock(writer, $"for (int i = 0; i < {repeaterSpan}.Length; i++)")) { EmitTimeoutCheck(writer, hasTimeout); string tmpTextSpanLocal = sliceSpan; // we want EmitSingleChar to refer to this temporary int tmpSliceStaticPos = sliceStaticPos; sliceSpan = repeaterSpan; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: "i"); sliceSpan = tmpTextSpanLocal; sliceStaticPos = tmpSliceStaticPos; } sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; Span<char> setChars = stackalloc char[5]; // 5 is max optimized by IndexOfAny today int numSetChars = 0; string iterationLocal = ReserveName("iteration"); if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOf({sliceSpan}"); if (sliceStaticPos > 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine($", {Literal(node.Ch)});"); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it should // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}"); if (sliceStaticPos != 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine(numSetChars switch { 2 => $", {Literal(setChars[0])}, {Literal(setChars[1])});", 3 => $", {Literal(setChars[0])}, {Literal(setChars[1])}, {Literal(setChars[2])});", _ => $", {Literal(setChars.Slice(0, numSetChars).ToString())});", }); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. TransferSliceStaticPosToPos(); writer.WriteLine($"int {iterationLocal} = inputSpan.Length - pos;"); } else { // For everything else, do a normal loop. string expr = $"{sliceSpan}[{iterationLocal}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } if (minIterations != 0 || maxIterations != int.MaxValue) { // For any loops other than * loops, transfer text pos to pos in // order to zero it out to be able to use the single iteration variable // for both iteration count and indexer. TransferSliceStaticPosToPos(); } writer.WriteLine($"int {iterationLocal} = {sliceStaticPos};"); sliceStaticPos = 0; string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}(uint){iterationLocal} < (uint){sliceSpan}.Length && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } // Check to ensure we've found at least min iterations. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationLocal, minIterations)})")) { Goto(doneLabel); } writer.WriteLine(); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({iterationLocal});"); writer.WriteLine($"pos += {iterationLocal};"); } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); string expr = $"{sliceSpan}[{sliceStaticPos}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } string spaceAvailable = sliceStaticPos != 0 ? $"(uint){sliceSpan}.Length > (uint){sliceStaticPos}" : $"!{sliceSpan}.IsEmpty"; using (EmitBlock(writer, $"if ({spaceAvailable} && {expr})")) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice(1);"); writer.WriteLine($"pos++;"); } } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. string i = ReserveName("loop_iteration"); using (EmitBlock(writer, $"for (int {i} = 0; {i} < {node.M}; {i}++)")) { EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs } } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string originalDoneLabel = doneLabel; string startingPos = ReserveName("loop_starting_pos"); string iterationCount = ReserveName("loop_iteration"); string body = ReserveName("LoopBody"); string endLoop = ReserveName("LoopEnd"); additionalDeclarations.Add($"int {iterationCount} = 0, {startingPos} = 0;"); writer.WriteLine($"{iterationCount} = 0;"); writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos" } : new[] { startingPos, "pos" }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); writer.WriteLine(); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. using (EmitBlock(writer, (minIterations > 0, maxIterations == int.MaxValue) switch { (true, true) => $"if (pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)})", (true, false) => $"if ((pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)}) && {CountIsLessThan(iterationCount, maxIterations)})", (false, true) => $"if (pos != {startingPos})", (false, false) => $"if (pos != {startingPos} && {CountIsLessThan(iterationCount, maxIterations)})", })) { Goto(body); } // We've matched as many iterations as we can with this configuration. Jump to what comes after the loop. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop("pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (minIterations > 0) { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(childBacktracks ? doneLabel : originalDoneLabel); } } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { Goto(endLoop); writer.WriteLine(); string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state EmitStackPush(startingPos, iterationCount); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(iterationCount, startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } } // Gets a comparison for whether the value is less than the upper bound. static string CountIsLessThan(string value, int exclusiveUpper) => exclusiveUpper == 1 ? $"{value} == 0" : $"{value} < {exclusiveUpper}"; // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(string capturepos) { string name = "UncaptureUntil"; if (!additionalLocalFunctions.ContainsKey(name)) { var lines = new string[9]; lines[0] = "// <summary>Undo captures until we reach the specified capture position.</summary>"; lines[1] = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"void {name}(int capturepos)"; lines[3] = "{"; lines[4] = " while (base.Crawlpos() > capturepos)"; lines[5] = " {"; lines[6] = " base.Uncapture();"; lines[7] = " }"; lines[8] = "}"; additionalLocalFunctions.Add(name, lines); } writer.WriteLine($"{name}({capturepos});"); } /// <summary>Pushes values on to the backtracking stack.</summary> void EmitStackPush(params string[] args) { Debug.Assert(args.Length is >= 1); string function = $"StackPush{args.Length}"; additionalDeclarations.Add("int stackpos = 0;"); if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[24 + args.Length]; lines[0] = $"// <summary>Push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[3] = $"{{"; lines[4] = $" // If there's space available for {(args.Length > 1 ? $"all {args.Length} values, store them" : "the value, store it")}."; lines[5] = $" int[] s = stack;"; lines[6] = $" int p = pos;"; lines[7] = $" if ((uint){(args.Length > 1 ? $"(p + {args.Length - 1})" : "p")} < (uint)s.Length)"; lines[8] = $" {{"; for (int i = 0; i < args.Length; i++) { lines[9 + i] = $" s[p{(i == 0 ? "" : $" + {i}")}] = arg{i};"; } lines[9 + args.Length] = args.Length > 1 ? $" pos += {args.Length};" : " pos++;"; lines[10 + args.Length] = $" return;"; lines[11 + args.Length] = $" }}"; lines[12 + args.Length] = $""; lines[13 + args.Length] = $" // Otherwise, resize the stack to make room and try again."; lines[14 + args.Length] = $" WithResize(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[15 + args.Length] = $""; lines[16 + args.Length] = $" // <summary>Resize the backtracking stack array and push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the stack.</summary>"; lines[17 + args.Length] = $" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; lines[18 + args.Length] = $" static void WithResize(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[19 + args.Length] = $" {{"; lines[20 + args.Length] = $" global::System.Array.Resize(ref stack, (pos + {args.Length - 1}) * 2);"; lines[21 + args.Length] = $" {function}(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[22 + args.Length] = $" }}"; lines[23 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(ref base.runstack!, ref stackpos, {string.Join(", ", args)});"); } /// <summary>Pops values from the backtracking stack into the specified locations.</summary> void EmitStackPop(params string[] args) { Debug.Assert(args.Length is >= 1); if (args.Length == 1) { writer.WriteLine($"{args[0]} = {StackPop()};"); return; } string function = $"StackPop{args.Length}"; if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[5 + args.Length]; lines[0] = $"// <summary>Pop {args.Length} value{(args.Length == 1 ? "" : "s")} from the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(int[] stack, ref int pos{FormatN(", out int arg{0}", args.Length)})"; lines[3] = $"{{"; for (int i = 0; i < args.Length; i++) { lines[4 + i] = $" arg{i} = stack[--pos];"; } lines[4 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(base.runstack, ref stackpos, out {string.Join(", out ", args)});"); } /// <summary>Expression for popping the next item from the backtracking stack.</summary> string StackPop() => "base.runstack![--stackpos]"; /// <summary>Concatenates the strings resulting from formatting the format string with the values [0, count).</summary> static string FormatN(string format, int count) => string.Concat(from i in Enumerable.Range(0, count) select string.Format(format, i)); } private static bool EmitLoopTimeoutCounterIfNeeded(IndentedTextWriter writer, RegexMethod rm) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("int loopTimeoutCounter = 0;"); return true; } return false; } /// <summary>Emits a timeout check.</summary> private static void EmitTimeoutCheck(IndentedTextWriter writer, bool hasTimeout) { const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling. if (hasTimeout) { // Increment counter for each loop iteration. // Emit code to check the timeout every 2048th iteration. using (EmitBlock(writer, $"if (++loopTimeoutCounter == {LoopTimeoutCheckCount})")) { writer.WriteLine("loopTimeoutCounter = 0;"); writer.WriteLine("base.CheckTimeout();"); } writer.WriteLine(); } } private static bool EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(IndentedTextWriter writer, RegexMethod rm, AnalysisResults analysis) { if (analysis.HasIgnoreCase && ((RegexOptions)rm.Options & RegexOptions.CultureInvariant) == 0) { writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); return true; } return false; } private static bool UseToLowerInvariant(bool hasTextInfo, RegexOptions options) => !hasTextInfo || (options & RegexOptions.CultureInvariant) != 0; private static string ToLower(bool hasTextInfo, RegexOptions options, string expression) => UseToLowerInvariant(hasTextInfo, options) ? $"char.ToLowerInvariant({expression})" : $"textInfo.ToLower({expression})"; private static string ToLowerIfNeeded(bool hasTextInfo, RegexOptions options, string expression, bool toLower) => toLower ? ToLower(hasTextInfo, options, expression) : expression; private static string MatchCharacterClass(bool hasTextInfo, RegexOptions options, string chExpr, string charClass, bool caseInsensitive, bool negate, HashSet<string> additionalDeclarations, ref RequiredHelperFunctions requiredHelpers) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // ideally this could just be "return true;", but we need to evaluate the expression for its side effects return $"({chExpr} {(negate ? "<" : ">=")} 0)"; // a char is unsigned and thus won't ever be negative case RegexCharClass.DigitClass: case RegexCharClass.NotDigitClass: negate ^= charClass == RegexCharClass.NotDigitClass; return $"{(negate ? "!" : "")}char.IsDigit({chExpr})"; case RegexCharClass.SpaceClass: case RegexCharClass.NotSpaceClass: negate ^= charClass == RegexCharClass.NotSpaceClass; return $"{(negate ? "!" : "")}char.IsWhiteSpace({chExpr})"; case RegexCharClass.WordClass: case RegexCharClass.NotWordClass: requiredHelpers |= RequiredHelperFunctions.IsWordChar; negate ^= charClass == RegexCharClass.NotWordClass; return $"{(negate ? "!" : "")}IsWordChar({chExpr})"; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant(hasTextInfo, options); if (!invariant) { chExpr = ToLower(hasTextInfo, options, chExpr); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { negate ^= RegexCharClass.IsNegated(charClass); return lowInclusive == highInclusive ? $"({chExpr} {(negate ? "!=" : "==")} {Literal(lowInclusive)})" : $"(((uint){chExpr}) - {Literal(lowInclusive)} {(negate ? ">" : "<=")} (uint)({Literal(highInclusive)} - {Literal(lowInclusive)}))"; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { negate ^= negated; return $"(char.GetUnicodeCategory({chExpr}) {(negate ? "!=" : "==")} global::System.Globalization.UnicodeCategory.{category})"; } // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it may be cheaper and smaller to compare against each than it is to use a lookup table. We can also special-case // the very common case with case insensitivity of two characters next to each other being the upper and lowercase // ASCII variants of each other, in which case we can use bit manipulation to avoid a comparison. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int mask; switch (RegexCharClass.GetSetChars(charClass, setChars)) { case 2: if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) { return $"(({chExpr} | 0x{mask:X}) {(negate ? "!=" : "==")} {Literal((char)(setChars[1] | mask))})"; } additionalDeclarations.Add("char ch;"); return negate ? $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}))" : $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}))"; case 3: additionalDeclarations.Add("char ch;"); return (negate, RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) switch { (false, false) => $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}) | (ch == {Literal(setChars[2])}))", (true, false) => $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}) & (ch != {Literal(setChars[2])}))", (false, true) => $"((((ch = {chExpr}) | 0x{mask:X}) == {Literal((char)(setChars[1] | mask))}) | (ch == {Literal(setChars[2])}))", (true, true) => $"((((ch = {chExpr}) | 0x{mask:X}) != {Literal((char)(setChars[1] | mask))}) & (ch != {Literal(setChars[2])}))", }; } } // All options after this point require a ch local. additionalDeclarations.Add("char ch;"); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) return negate ? $"((ch = {chExpr}) < 128 || !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) >= 128 && global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. return negate ? $"((ch = {chExpr}) >= 128 && !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) < 128 || global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = StringExtensions.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. return negate ? $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. return negate ? $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. return (negate, invariant) switch { (false, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (true, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (false, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", (true, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", }; } /// <summary> /// Replaces <see cref="AdditionalDeclarationsPlaceholder"/> in <paramref name="writer"/> with /// all of the variable declarations in <paramref name="declarations"/>. /// </summary> /// <param name="writer">The writer around a StringWriter to have additional declarations inserted into.</param> /// <param name="declarations">The additional declarations to insert.</param> /// <param name="position">The position into the writer at which to insert the additional declarations.</param> /// <param name="indent">The indentation to use for the additional declarations.</param> private static void ReplaceAdditionalDeclarations(IndentedTextWriter writer, HashSet<string> declarations, int position, int indent) { if (declarations.Count != 0) { var tmp = new StringBuilder(); foreach (string decl in declarations.OrderBy(s => s)) { for (int i = 0; i < indent; i++) { tmp.Append(IndentedTextWriter.DefaultTabString); } tmp.AppendLine(decl); } ((StringWriter)writer.InnerWriter).GetStringBuilder().Insert(position, tmp.ToString()); } } /// <summary>Formats the character as valid C#.</summary> private static string Literal(char c) => SymbolDisplay.FormatLiteral(c, quote: true); /// <summary>Formats the string as valid C#.</summary> private static string Literal(string s) => SymbolDisplay.FormatLiteral(s, quote: true); private static string Literal(RegexOptions options) { string s = options.ToString(); if (int.TryParse(s, out _)) { // The options were formatted as an int, which means the runtime couldn't // produce a textual representation. So just output casting the value as an int. return $"(global::System.Text.RegularExpressions.RegexOptions)({(int)options})"; } // Parse the runtime-generated "Option1, Option2" into each piece and then concat // them back together. string[] parts = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { parts[i] = "global::System.Text.RegularExpressions.RegexOptions." + parts[i].Trim(); } return string.Join(" | ", parts); } /// <summary>Gets a textual description of the node fit for rendering in a comment in source.</summary> private static string DescribeNode(RegexNode node, AnalysisResults analysis) => node.Kind switch { RegexNodeKind.Alternate => $"Match with {node.ChildCount()} alternative expressions{(analysis.IsAtomicByAncestor(node) ? ", atomically" : "")}.", RegexNodeKind.Atomic => $"Atomic group.", RegexNodeKind.Beginning => "Match if at the beginning of the string.", RegexNodeKind.Bol => "Match if at the beginning of a line.", RegexNodeKind.Boundary => $"Match if at a word boundary.", RegexNodeKind.Capture when node.M == -1 && node.N != -1 => $"Non-capturing balancing group. Uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N != -1 => $"Balancing group. Captures the {DescribeCapture(node.M, analysis)} and uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N == -1 => $"{DescribeCapture(node.M, analysis)}.", RegexNodeKind.Concatenate => "Match a sequence of expressions.", RegexNodeKind.ECMABoundary => $"Match if at a word boundary (according to ECMAScript rules).", RegexNodeKind.Empty => $"Match an empty string.", RegexNodeKind.End => "Match if at the end of the string.", RegexNodeKind.EndZ => "Match if at the end of the string or if before an ending newline.", RegexNodeKind.Eol => "Match if at the end of a line.", RegexNodeKind.Loop or RegexNodeKind.Lazyloop => node.M == 0 && node.N == 1 ? $"Optional ({(node.Kind is RegexNodeKind.Loop ? "greedy" : "lazy")})." : $"Loop {DescribeLoop(node, analysis)}.", RegexNodeKind.Multi => $"Match the string {Literal(node.Str!)}.", RegexNodeKind.NonBoundary => $"Match if at anything other than a word boundary.", RegexNodeKind.NonECMABoundary => $"Match if at anything other than a word boundary (according to ECMAScript rules).", RegexNodeKind.Nothing => $"Fail to match.", RegexNodeKind.Notone => $"Match any character other than {Literal(node.Ch)}.", RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy => $"Match a character other than {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.One => $"Match {Literal(node.Ch)}.", RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.NegativeLookaround => $"Zero-width negative lookahead assertion.", RegexNodeKind.Backreference => $"Match the same text as matched by the {DescribeCapture(node.M, analysis)}.", RegexNodeKind.PositiveLookaround => $"Zero-width positive lookahead assertion.", RegexNodeKind.Set => $"Match {DescribeSet(node.Str!)}.", RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => $"Match {DescribeSet(node.Str!)} {DescribeLoop(node, analysis)}.", RegexNodeKind.Start => "Match if at the start position.", RegexNodeKind.ExpressionConditional => $"Conditionally match one of two expressions depending on whether an initial expression matches.", RegexNodeKind.BackreferenceConditional => $"Conditionally match one of two expressions depending on whether the {DescribeCapture(node.M, analysis)} matched.", RegexNodeKind.UpdateBumpalong => $"Advance the next matching position.", _ => $"Unknown node type {node.Kind}", }; /// <summary>Gets an identifer to describe a capture group.</summary> private static string DescribeCapture(int capNum, AnalysisResults analysis) { // If we can get a capture name from the captures collection and it's not just a numerical representation of the group, use it. string name = RegexParser.GroupNameFromNumber(analysis.RegexTree.CaptureNumberSparseMapping, analysis.RegexTree.CaptureNames, analysis.RegexTree.CaptureCount, capNum); if (!string.IsNullOrEmpty(name) && (!int.TryParse(name, out int id) || id != capNum)) { name = Literal(name); } else { // Otherwise, create a numerical description of the capture group. int tens = capNum % 10; name = tens is >= 1 and <= 3 && capNum % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 tens switch { 1 => $"{capNum}st", 2 => $"{capNum}nd", _ => $"{capNum}rd", } : $"{capNum}th"; } return $"{name} capture group"; } /// <summary>Gets a textual description of what characters match a set.</summary> private static string DescribeSet(string charClass) => charClass switch { RegexCharClass.AnyClass => "any character", RegexCharClass.DigitClass => "a Unicode digit", RegexCharClass.ECMADigitClass => "'0' through '9'", RegexCharClass.ECMASpaceClass => "a whitespace character (ECMA)", RegexCharClass.ECMAWordClass => "a word character (ECMA)", RegexCharClass.NotDigitClass => "any character other than a Unicode digit", RegexCharClass.NotECMADigitClass => "any character other than '0' through '9'", RegexCharClass.NotECMASpaceClass => "any character other than a space character (ECMA)", RegexCharClass.NotECMAWordClass => "any character other than a word character (ECMA)", RegexCharClass.NotSpaceClass => "any character other than a space character", RegexCharClass.NotWordClass => "any character other than a word character", RegexCharClass.SpaceClass => "a whitespace character", RegexCharClass.WordClass => "a word character", _ => $"a character in the set {RegexCharClass.DescribeSet(charClass)}", }; /// <summary>Writes a textual description of the node tree fit for rending in source.</summary> /// <param name="writer">The writer to which the description should be written.</param> /// <param name="node">The node being written.</param> /// <param name="prefix">The prefix to write at the beginning of every line, including a "//" for a comment.</param> /// <param name="analyses">Analysis of the tree</param> /// <param name="depth">The depth of the current node.</param> private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, AnalysisResults analysis, int depth = 0) { bool skip = node.Kind switch { // For concatenations, flatten the contents into the parent, but only if the parent isn't a form of alternation, // where each branch is considered to be independent rather than a concatenation. RegexNodeKind.Concatenate when node.Parent is not { Kind: RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional } => true, // For atomic, skip the node if we'll instead render the atomic label as part of rendering the child. RegexNodeKind.Atomic when node.Child(0).Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop or RegexNodeKind.Alternate => true, // Don't skip anything else. _ => false, }; if (!skip) { string tag = node.Parent?.Kind switch { RegexNodeKind.ExpressionConditional when node.Parent.Child(0) == node => "Condition: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(1) == node => "Matched: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(2) == node => "Not Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(0) == node => "Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(1) == node => "Not Matched: ", _ => "", }; // Write out the line for the node. const char BulletPoint = '\u25CB'; writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node, analysis)}"); } // Recur into each of its children. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { int childDepth = skip ? depth : depth + 1; DescribeExpression(writer, node.Child(i), prefix, analysis, childDepth); } } /// <summary>Gets a textual description of a loop's style and bounds.</summary> private static string DescribeLoop(RegexNode node, AnalysisResults analysis) { string style = node.Kind switch { _ when node.M == node.N => "exactly", RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic => "atomically", RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop => "greedily", RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy => "lazily", RegexNodeKind.Loop => analysis.IsAtomicByAncestor(node) ? "greedily and atomically" : "greedily", _ /* RegexNodeKind.Lazyloop */ => analysis.IsAtomicByAncestor(node) ? "lazily and atomically" : "lazily", }; string bounds = node.M == node.N ? $" {node.M} times" : (node.M, node.N) switch { (0, int.MaxValue) => " any number of times", (1, int.MaxValue) => " at least once", (2, int.MaxValue) => " at least twice", (_, int.MaxValue) => $" at least {node.M} times", (0, 1) => ", optionally", (0, _) => $" at most {node.N} times", _ => $" at least {node.M} and at most {node.N} times" }; return style + bounds; } private static FinishEmitScope EmitScope(IndentedTextWriter writer, string title, bool faux = false) => EmitBlock(writer, $"// {title}", faux: faux); private static FinishEmitScope EmitBlock(IndentedTextWriter writer, string? clause, bool faux = false) { if (clause is not null) { writer.WriteLine(clause); } writer.WriteLine(faux ? "//{" : "{"); writer.Indent++; return new FinishEmitScope(writer, faux); } private static void EmitAdd(IndentedTextWriter writer, string variable, int value) { if (value == 0) { return; } writer.WriteLine( value == 1 ? $"{variable}++;" : value == -1 ? $"{variable}--;" : value > 0 ? $"{variable} += {value};" : value < 0 && value > int.MinValue ? $"{variable} -= {-value};" : $"{variable} += {value.ToString(CultureInfo.InvariantCulture)};"); } private readonly struct FinishEmitScope : IDisposable { private readonly IndentedTextWriter _writer; private readonly bool _faux; public FinishEmitScope(IndentedTextWriter writer, bool faux) { _writer = writer; _faux = faux; } public void Dispose() { if (_writer is not null) { _writer.Indent--; _writer.WriteLine(_faux ? "//}" : "}"); } } } /// <summary>Bit flags indicating which additional helpers should be emitted into the regex class.</summary> [Flags] private enum RequiredHelperFunctions { /// <summary>No additional functions are required.</summary> None = 0b0, /// <summary>The IsWordChar helper is required.</summary> IsWordChar = 0b1, /// <summary>The IsBoundary helper is required.</summary> IsBoundary = 0b10, /// <summary>The IsECMABoundary helper is required.</summary> IsECMABoundary = 0b100 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; // NOTE: The logic in this file is largely a copy of logic in RegexCompiler, emitting C# instead of MSIL. // Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations // are concerned. namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { /// <summary>Code for a [GeneratedCode] attribute to put on the top-level generated members.</summary> private static readonly string s_generatedCodeAttribute = $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(RegexGenerator).Assembly.GetName().Name}\", \"{typeof(RegexGenerator).Assembly.GetName().Version}\")]"; /// <summary>Header comments and usings to include at the top of every generated file.</summary> private static readonly string[] s_headers = new string[] { "// <auto-generated/>", "#nullable enable", "#pragma warning disable CS0162 // Unreachable code", "#pragma warning disable CS0164 // Unreferenced label", "#pragma warning disable CS0219 // Variable assigned but never used", "", }; /// <summary>Generates the code for one regular expression class.</summary> private static (string, ImmutableArray<Diagnostic>) EmitRegexType(RegexType regexClass, bool allowUnsafe) { var sb = new StringBuilder(1024); var writer = new IndentedTextWriter(new StringWriter(sb)); // Emit the namespace if (!string.IsNullOrWhiteSpace(regexClass.Namespace)) { writer.WriteLine($"namespace {regexClass.Namespace}"); writer.WriteLine("{"); writer.Indent++; } // Emit containing types RegexType? parent = regexClass.ParentClass; var parentClasses = new Stack<string>(); while (parent is not null) { parentClasses.Push($"partial {parent.Keyword} {parent.Name}"); parent = parent.ParentClass; } while (parentClasses.Count != 0) { writer.WriteLine($"{parentClasses.Pop()}"); writer.WriteLine("{"); writer.Indent++; } // Emit the direct parent type writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name}"); writer.WriteLine("{"); writer.Indent++; // Generate a name to describe the regex instance. This includes the method name // the user provided and a non-randomized (for determinism) hash of it to try to make // the name that much harder to predict. Debug.Assert(regexClass.Method is not null); string generatedName = $"GeneratedRegex_{regexClass.Method.MethodName}_"; generatedName += ComputeStringHash(generatedName).ToString("X"); // Generate the regex type ImmutableArray<Diagnostic> diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName, allowUnsafe); while (writer.Indent != 0) { writer.Indent--; writer.WriteLine("}"); } writer.Flush(); return (sb.ToString(), diagnostics); // FNV-1a hash function. The actual algorithm used doesn't matter; just something simple // to create a deterministic, pseudo-random value that's based on input text. static uint ComputeStringHash(string s) { uint hashCode = 2166136261; foreach (char c in s) { hashCode = (c ^ hashCode) * 16777619; } return hashCode; } } /// <summary>Gets whether a given regular expression method is supported by the code generator.</summary> private static bool SupportsCodeGeneration(RegexMethod rm, out string? reason) { RegexNode root = rm.Tree.Root; if (!root.SupportsCompilation(out reason)) { return false; } if (ExceedsMaxDepthForSimpleCodeGeneration(root, allowedDepth: 40)) { // Deep RegexNode trees can result in emitting C# code that exceeds C# compiler // limitations, leading to "CS8078: An expression is too long or complex to compile". // Place an artificial limit on max tree depth in order to mitigate such issues. // The allowed depth can be tweaked as needed;its exceedingly rare to find // expressions with such deep trees. reason = "the regex will result in code that may exceed C# compiler limits"; return false; } return true; static bool ExceedsMaxDepthForSimpleCodeGeneration(RegexNode node, int allowedDepth) { if (allowedDepth <= 0) { return true; } int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { if (ExceedsMaxDepthForSimpleCodeGeneration(node.Child(i), allowedDepth - 1)) { return true; } } return false; } } /// <summary>Generates the code for a regular expression method.</summary> private static ImmutableArray<Diagnostic> EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id, bool allowUnsafe) { string patternExpression = Literal(rm.Pattern); string optionsExpression = Literal(rm.Options); string timeoutExpression = rm.MatchTimeout == Timeout.Infinite ? "global::System.Threading.Timeout.InfiniteTimeSpan" : $"global::System.TimeSpan.FromMilliseconds({rm.MatchTimeout.ToString(CultureInfo.InvariantCulture)})"; writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine($"{rm.Modifiers} global::System.Text.RegularExpressions.Regex {rm.MethodName}() => {id}.Instance;"); writer.WriteLine(); writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"); writer.WriteLine($"{(writer.Indent != 0 ? "private" : "internal")} sealed class {id} : global::System.Text.RegularExpressions.Regex"); writer.WriteLine("{"); writer.Write(" public static global::System.Text.RegularExpressions.Regex Instance { get; } = "); // If we can't support custom generation for this regex, spit out a Regex constructor call. if (!SupportsCodeGeneration(rm, out string? reason)) { writer.WriteLine(); writer.WriteLine($"// Cannot generate Regex-derived implementation because {reason}."); writer.WriteLine($"new global::System.Text.RegularExpressions.Regex({patternExpression}, {optionsExpression}, {timeoutExpression});"); writer.WriteLine("}"); return ImmutableArray.Create(Diagnostic.Create(DiagnosticDescriptors.LimitedSourceGeneration, rm.MethodSyntax.GetLocation())); } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(rm.Tree); writer.WriteLine($"new {id}();"); writer.WriteLine(); writer.WriteLine($" private {id}()"); writer.WriteLine($" {{"); writer.WriteLine($" base.pattern = {patternExpression};"); writer.WriteLine($" base.roptions = {optionsExpression};"); writer.WriteLine($" base.internalMatchTimeout = {timeoutExpression};"); writer.WriteLine($" base.factory = new RunnerFactory();"); if (rm.Tree.CaptureNumberSparseMapping is not null) { writer.Write(" base.Caps = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNumberSparseMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNameToNumberMapping is not null) { writer.Write(" base.CapNames = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNameToNumberMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNames is not null) { writer.Write(" base.capslist = new string[] {"); string separator = ""; foreach (string s in rm.Tree.CaptureNames) { writer.Write(separator); writer.Write(Literal(s)); separator = ", "; } writer.WriteLine(" };"); } writer.WriteLine($" base.capsize = {rm.Tree.CaptureCount};"); writer.WriteLine($" }}"); writer.WriteLine(" "); writer.WriteLine($" private sealed class RunnerFactory : global::System.Text.RegularExpressions.RegexRunnerFactory"); writer.WriteLine($" {{"); writer.WriteLine($" protected override global::System.Text.RegularExpressions.RegexRunner CreateInstance() => new Runner();"); writer.WriteLine(); writer.WriteLine($" private sealed class Runner : global::System.Text.RegularExpressions.RegexRunner"); writer.WriteLine($" {{"); // Main implementation methods writer.WriteLine(" // Description:"); DescribeExpression(writer, rm.Tree.Root.Child(0), " // ", analysis); // skip implicit root capture writer.WriteLine(); writer.WriteLine($" protected override void Scan(global::System.ReadOnlySpan<char> text)"); writer.WriteLine($" {{"); writer.Indent += 4; EmitScan(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); writer.WriteLine($" private bool TryFindNextPossibleStartingPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; RequiredHelperFunctions requiredHelpers = EmitTryFindNextPossibleStartingPosition(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); if (allowUnsafe) { writer.WriteLine($" [global::System.Runtime.CompilerServices.SkipLocalsInit]"); } writer.WriteLine($" private bool TryMatchAtCurrentPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; requiredHelpers |= EmitTryMatchAtCurrentPosition(writer, rm, id, analysis); writer.Indent -= 4; writer.WriteLine($" }}"); if ((requiredHelpers & RequiredHelperFunctions.IsWordChar) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character is part of the [\\w] set.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsWordChar(char ch)"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.ReadOnlySpan<byte> ascii = new byte[]"); writer.WriteLine($" {{"); writer.WriteLine($" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,"); writer.WriteLine($" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07"); writer.WriteLine($" }};"); writer.WriteLine(); writer.WriteLine($" int chDiv8 = ch >> 3;"); writer.WriteLine($" return (uint)chDiv8 < (uint)ascii.Length ?"); writer.WriteLine($" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :"); writer.WriteLine($" global::System.Globalization.CharUnicodeInfo.GetUnicodeCategory(ch) switch"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.UppercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.LowercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.TitlecaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ModifierLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.OtherLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.NonSpacingMark or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.DecimalDigitNumber or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ConnectorPunctuation => true,"); writer.WriteLine($" _ => false,"); writer.WriteLine($" }};"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsBoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsBoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsBoundaryWordChar(char ch) =>"); writer.WriteLine($" IsWordChar(ch) || (ch == '\\u200C' | ch == '\\u200D');"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsECMABoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsECMABoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsECMAWordChar(char ch) =>"); writer.WriteLine($" ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter"); writer.WriteLine($" (((uint)ch - '0') < 10) || // digit"); writer.WriteLine($" ch == '_' || // underscore"); writer.WriteLine($" ch == '\\u0130'; // latin capital letter I with dot above"); writer.WriteLine($" }}"); } writer.WriteLine($" }}"); writer.WriteLine($" }}"); writer.WriteLine("}"); return ImmutableArray<Diagnostic>.Empty; static void AppendHashtableContents(IndentedTextWriter writer, Hashtable ht) { IDictionaryEnumerator en = ht.GetEnumerator(); string separator = ""; while (en.MoveNext()) { writer.Write(separator); separator = ", "; writer.Write(" { "); if (en.Key is int key) { writer.Write(key); } else { writer.Write($"\"{en.Key}\""); } writer.Write($", {en.Value} }} "); } } } /// <summary>Emits the body of the Scan method override.</summary> private static void EmitScan(IndentedTextWriter writer, RegexMethod rm, string id) { using (EmitBlock(writer, "while (TryFindNextPossibleStartingPosition(text))")) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("base.CheckTimeout();"); writer.WriteLine(); } writer.WriteLine("// If we find a match on the current position, or we have reached the end of the input, we are done."); using (EmitBlock(writer, "if (TryMatchAtCurrentPosition(text) || base.runtextpos == text.Length)")) { writer.WriteLine("return;"); } writer.WriteLine(); writer.WriteLine("base.runtextpos++;"); } } /// <summary>Emits the body of the TryFindNextPossibleStartingPosition.</summary> private static RequiredHelperFunctions EmitTryFindNextPossibleStartingPosition(IndentedTextWriter writer, RegexMethod rm, string id) { RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; bool hasTextInfo = false; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); // Emit locals initialization writer.WriteLine("int pos = base.runtextpos;"); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; writer.WriteLine(); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = rm.Tree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); string clause = minRequiredLength switch { 0 => "if (pos <= inputSpan.Length)", 1 => "if (pos < inputSpan.Length)", _ => $"if (pos < inputSpan.Length - {minRequiredLength - 1})" }; using (EmitBlock(writer, clause)) { // Emit any anchors. if (!EmitAnchors()) { // Either anchors weren't specified, or they don't completely root all matches to a specific location. // If whatever search operation we need to perform entails case-insensitive operations // that weren't already handled via creation of sets, we need to get an store the // TextInfo object to use (unless RegexOptions.CultureInvariant was specified). EmitTextInfo(writer, ref hasTextInfo, rm); // Emit the code for whatever find mode has been determined. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: writer.WriteLine("return true;"); break; } } } writer.WriteLine(); const string NoStartingPositionFound = "NoStartingPositionFound"; writer.WriteLine("// No starting position found"); writer.WriteLine($"{NoStartingPositionFound}:"); writer.WriteLine("base.runtextpos = inputSpan.Length;"); writer.WriteLine("return false;"); // We're done. Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); return requiredHelpers; // Emit a goto for the specified label. void Goto(string label) => writer.WriteLine($"goto {label};"); // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos > 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: writer.WriteLine("// Start \\G anchor"); using (EmitBlock(writer, "if (pos > base.runtextstart)")) { Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1)")) { writer.WriteLine("base.runtextpos = inputSpan.Length - 1;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { writer.WriteLine("base.runtextpos = inputSpan.Length;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length, minus 1 (for a possible ending \n). writer.WriteLine("// Trailing end \\Z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1};"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: // Jump to the end, minus the min required length, which in this case is actually the fixed length. writer.WriteLine("// Trailing end \\z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength};"); } writer.WriteLine("return true;"); return true; } // Now handle anchors that boost the position but may not determine immediate success or failure. switch (regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. writer.WriteLine("// Beginning-of-line anchor"); using (EmitBlock(writer, "if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');"); using (EmitBlock(writer, "if ((uint)newlinePos > inputSpan.Length - pos - 1)")) { Goto(NoStartingPositionFound); } writer.WriteLine("pos = newlinePos + pos + 1;"); // We've updated the position. Make sure there's still enough room in the input for a possible match. using (EmitBlock(writer, minRequiredLength switch { 0 => "if (pos > inputSpan.Length)", 1 => "if (pos >= inputSpan.Length)", _ => $"if (pos > inputSpan.Length - {minRequiredLength})" })) { Goto(NoStartingPositionFound); } } writer.WriteLine(); break; } switch (regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength};"); } writer.WriteLine(); break; case RegexNodeKind.EndZ when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\Z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength + 1})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength + 1};"); } writer.WriteLine(); break; } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf(string prefix) { writer.WriteLine($"int i = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), {Literal(prefix)});"); writer.WriteLine("if (i >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + i;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; FinishEmitScope loopBlock = default; if (needLoop) { writer.WriteLine("global::System.ReadOnlySpan<char> span = inputSpan.Slice(pos);"); string upperBound = "span.Length" + (setsToUse > 1 || primarySet.Distance != 0 ? $" - {minRequiredLength - 1}" : ""); loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)"); } if (canUseIndexOf) { string span = needLoop ? "span" : "inputSpan.Slice(pos)"; span = (needLoop, primarySet.Distance) switch { (false, 0) => span, (true, 0) => $"{span}.Slice(i)", (false, _) => $"{span}.Slice({primarySet.Distance})", (true, _) => $"{span}.Slice(i + {primarySet.Distance})", }; string indexOf = primarySet.Chars!.Length switch { 1 => $"global::System.MemoryExtensions.IndexOf({span}, {Literal(primarySet.Chars[0])})", 2 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])})", 3 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])}, {Literal(primarySet.Chars[2])})", _ => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(new string(primarySet.Chars))})", }; if (needLoop) { writer.WriteLine($"int indexOfPos = {indexOf};"); using (EmitBlock(writer, "if (indexOfPos < 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("i += indexOfPos;"); writer.WriteLine(); if (setsToUse > 1) { using (EmitBlock(writer, $"if (i >= span.Length - {minRequiredLength - 1})")) { Goto(NoStartingPositionFound); } writer.WriteLine(); } } else { writer.WriteLine($"int i = {indexOf};"); using (EmitBlock(writer, "if (i >= 0)")) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } setIndex = 1; } if (needLoop) { Debug.Assert(setIndex == 0 || setIndex == 1); bool hasCharClassConditions = false; if (setIndex < setsToUse) { // if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") && // ...) Debug.Assert(needLoop); int start = setIndex; for (; setIndex < setsToUse; setIndex++) { string spanIndex = $"span[i{(sets[setIndex].Distance > 0 ? $" + {sets[setIndex].Distance}" : "")}]"; string charInClassExpr = MatchCharacterClass(hasTextInfo, options, spanIndex, sets[setIndex].Set, sets[setIndex].CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers); if (setIndex == start) { writer.Write($"if ({charInClassExpr}"); } else { writer.WriteLine(" &&"); writer.Write($" {charInClassExpr}"); } } writer.WriteLine(")"); hasCharClassConditions = true; } using (hasCharClassConditions ? EmitBlock(writer, null) : default) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } loopBlock.Dispose(); } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); using (EmitBlock(writer, "while (true)")) { writer.WriteLine($"global::System.ReadOnlySpan<char> slice = inputSpan.Slice(pos);"); writer.WriteLine(); // Find the literal. If we can't find it, we're done searching. writer.Write("int i = global::System.MemoryExtensions."); writer.WriteLine( target.Literal.String is string literalString ? $"IndexOf(slice, {Literal(literalString)});" : target.Literal.Chars is not char[] literalChars ? $"IndexOf(slice, {Literal(target.Literal.Char)});" : literalChars.Length switch { 2 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])});", 3 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])}, {Literal(literalChars[2])});", _ => $"IndexOfAny(slice, {Literal(new string(literalChars))});", }); using (EmitBlock(writer, $"if (i < 0)")) { writer.WriteLine("break;"); } writer.WriteLine(); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. writer.WriteLine("int prev = i;"); writer.WriteLine($"while ((uint)--prev < (uint)slice.Length && {MatchCharacterClass(hasTextInfo, options, "slice[prev]", target.LoopNode.Str!, caseInsensitive: false, negate: false, additionalDeclarations, ref requiredHelpers)});"); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. writer.WriteLine($"if ((i - prev - 1) < {target.LoopNode.M})"); writer.WriteLine("{"); writer.WriteLine(" pos += i + 1;"); writer.WriteLine(" continue;"); writer.WriteLine("}"); } writer.WriteLine(); // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. writer.WriteLine("base.runtextpos = pos + prev + 1;"); writer.WriteLine("return true;"); } } // If a TextInfo is needed to perform ToLower operations, emits a local initialized to the TextInfo to use. static void EmitTextInfo(IndentedTextWriter writer, ref bool hasTextInfo, RegexMethod rm) { // Emit local to store current culture if needed if ((rm.Options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = rm.Tree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when rm.Tree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { hasTextInfo = true; writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); } } } } /// <summary>Emits the body of the TryMatchAtCurrentPosition.</summary> private static RequiredHelperFunctions EmitTryMatchAtCurrentPosition(IndentedTextWriter writer, RegexMethod rm, string id, AnalysisResults analysis) { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // Helper to define names. Names start unadorned, but as soon as there's repetition, // they begin to have a numbered suffix. var usedNames = new Dictionary<string, int>(); // Every RegexTree is rooted in the implicit Capture for the whole expression. // Skip the Capture node. We handle the implicit root capture specially. RegexNode node = regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. writer.WriteLine($"int start = base.runtextpos;"); writer.WriteLine($"int end = start + {(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1)};"); writer.WriteLine("base.Capture(0, start, end);"); writer.WriteLine("base.runtextpos = end;"); writer.WriteLine("return true;"); return requiredHelpers; case RegexNodeKind.Empty: // This case isn't common in production, but it's very common when first getting started with the // source generator and seeing what happens as you add more to expressions. When approaching // it from a learning perspective, this is very common, as it's the empty string you start with. writer.WriteLine("base.Capture(0, base.runtextpos, base.runtextpos);"); writer.WriteLine("return true;"); return requiredHelpers; } // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); var additionalLocalFunctions = new Dictionary<string, string[]>(); // Declare some locals. string sliceSpan = "slice"; writer.WriteLine("int pos = base.runtextpos;"); writer.WriteLine($"int original_pos = pos;"); bool hasTimeout = EmitLoopTimeoutCounterIfNeeded(writer, rm); bool hasTextInfo = EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(writer, rm, analysis); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(writer, defineLocal: true); writer.WriteLine(); // doneLabel starts out as the top-level label for the whole expression failing to match. However, // it may be changed by the processing of a node to point to whereever subsequent match failures // should jump to, in support of backtracking or other constructs. For example, before emitting // the code for a branch N, an alternation will set the the doneLabel to point to the label for // processing the next branch N+1: that way, any failures in the branch N's processing will // implicitly end up jumping to the right location without needing to know in what context it's used. string doneLabel = ReserveName("NoMatch"); string topLevelDoneLabel = doneLabel; // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // If we fall through to this place in the code, we've successfully matched the expression. writer.WriteLine(); writer.WriteLine("// The input matched."); if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); // TransferSliceStaticPosToPos would also slice, which isn't needed here } writer.WriteLine("base.runtextpos = pos;"); writer.WriteLine("base.Capture(0, original_pos, pos);"); writer.WriteLine("return true;"); // We're done with the match. // Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); // And emit any required helpers. if (additionalLocalFunctions.Count != 0) { foreach (KeyValuePair<string, string[]> localFunctions in additionalLocalFunctions.OrderBy(k => k.Key)) { writer.WriteLine(); foreach (string line in localFunctions.Value) { writer.WriteLine(line); } } } return requiredHelpers; // Helper to create a name guaranteed to be unique within the function. string ReserveName(string prefix) { usedNames.TryGetValue(prefix, out int count); usedNames[prefix] = count + 1; return count == 0 ? prefix : $"{prefix}{count}"; } // Helper to emit a label. As of C# 10, labels aren't statements of their own and need to adorn a following statement; // if a label appears just before a closing brace, then, it's a compilation error. To avoid issues there, this by // default implements a blank statement (a semicolon) after each label, but individual uses can opt-out of the semicolon // when it's known the label will always be followed by a statement. void MarkLabel(string label, bool emitSemicolon = true) => writer.WriteLine($"{label}:{(emitSemicolon ? ";" : "")}"); // Emits a goto to jump to the specified label. However, if the specified label is the top-level done label indicating // that the entire match has failed, we instead emit our epilogue, uncapturing if necessary and returning out of TryMatchAtCurrentPosition. void Goto(string label) { if (label == topLevelDoneLabel) { // We only get here in the code if the whole expression fails to match and jumps to // the original value of doneLabel. if (expressionHasCaptures) { EmitUncaptureUntil("0"); } writer.WriteLine("return false; // The input didn't match."); } else { writer.WriteLine($"goto {label};"); } } // Emits a case or default line followed by an indented body. void CaseGoto(string clause, string label) { writer.WriteLine(clause); writer.Indent++; Goto(label); writer.Indent--; } // Whether the node has RegexOptions.IgnoreCase set. static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan(IndentedTextWriter writer, bool defineLocal = false) { if (defineLocal) { writer.Write("global::System.ReadOnlySpan<char> "); } writer.WriteLine($"{sliceSpan} = inputSpan.Slice(pos);"); } // Emits the sum of a constant and a value from a local. string Sum(int constant, string? local = null) => local is null ? constant.ToString(CultureInfo.InvariantCulture) : constant == 0 ? local : $"{constant} + {local}"; // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) { Debug.Assert(requiredLength > 0); using (EmitBlock(writer, $"if ({SpanLengthCheck(requiredLength, dynamicRequiredLength)})")) { Goto(doneLabel); } } // Returns a length check for the current span slice. The check returns true if // the span isn't long enough for the specified length. string SpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) => dynamicRequiredLength is null && sliceStaticPos + requiredLength == 1 ? $"{sliceSpan}.IsEmpty" : $"(uint){sliceSpan}.Length < {Sum(sliceStaticPos + requiredLength, dynamicRequiredLength)}"; // Adds the value of sliceStaticPos into the pos local, slices slice by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos() { if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({sliceStaticPos});"); sliceStaticPos = 0; } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); string originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // If no child branch overlaps with another child branch, we can emit more streamlined code // that avoids checking unnecessary branches, e.g. with abc|def|ghi if the next character in // the input is 'a', we needn't try the def or ghi branches. A simple, relatively common case // of this is if every branch begins with a specific, unique character, in which case // the whole alternation can be treated as a simple switch, so we special-case that. However, // we can't goto _into_ switch cases, which means we can't use this approach if there's any // possibility of backtracking into the alternation. bool useSwitchedBranches = isAtomic; if (!useSwitchedBranches) { useSwitchedBranches = true; for (int i = 0; i < childCount; i++) { if (analysis.MayBacktrack(node.Child(i))) { useSwitchedBranches = false; break; } } } // Detect whether every branch begins with one or more unique characters. const int SetCharsSize = 5; // arbitrary limit (for IgnoreCase, we want this to be at least 3 to handle the vast majority of values) Span<char> setChars = stackalloc char[SetCharsSize]; if (useSwitchedBranches) { // Iterate through every branch, seeing if we can easily find a starting One, Multi, or small Set. // If we can, extract its starting char (or multiple in the case of a set), validate that all such // starting characters are unique relative to all the branches. var seenChars = new HashSet<char>(); for (int i = 0; i < childCount && useSwitchedBranches; i++) { // If it's not a One, Multi, or Set, we can't apply this optimization. // If it's IgnoreCase (and wasn't reduced to a non-IgnoreCase set), also ignore it to keep the logic simple. if (node.Child(i).FindBranchOneMultiOrSetStart() is not RegexNode oneMultiOrSet || (oneMultiOrSet.Options & RegexOptions.IgnoreCase) != 0) // TODO: https://github.com/dotnet/runtime/issues/61048 { useSwitchedBranches = false; break; } // If it's a One or a Multi, get the first character and add it to the set. // If it was already in the set, we can't apply this optimization. if (oneMultiOrSet.Kind is RegexNodeKind.One or RegexNodeKind.Multi) { if (!seenChars.Add(oneMultiOrSet.FirstCharOfOneOrMulti())) { useSwitchedBranches = false; break; } } else { // The branch begins with a set. Make sure it's a set of only a few characters // and get them. If we can't, we can't apply this optimization. Debug.Assert(oneMultiOrSet.Kind is RegexNodeKind.Set); int numChars; if (RegexCharClass.IsNegated(oneMultiOrSet.Str!) || (numChars = RegexCharClass.GetSetChars(oneMultiOrSet.Str!, setChars)) == 0) { useSwitchedBranches = false; break; } // Check to make sure each of the chars is unique relative to all other branches examined. foreach (char c in setChars.Slice(0, numChars)) { if (!seenChars.Add(c)) { useSwitchedBranches = false; break; } } } } } if (useSwitchedBranches) { // Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the // C# compiler to lower the C# switch statement with appropriate optimizations. In some // cases there are enough branches that the compiler will emit a jump table. In others // it'll optimize the order of checks in order to minimize the total number in the worst // case. In any case, we get easier to read and reason about C#. EmitSwitchedBranches(); } else { EmitAllBranches(); } return; // Emits the code for a switch-based alternation of non-overlapping branches. void EmitSwitchedBranches() { // We need at least 1 remaining character in the span, for the char to switch on. EmitSpanLengthCheck(1); writer.WriteLine(); // Emit a switch statement on the first char of each branch. using (EmitBlock(writer, $"switch ({sliceSpan}[{sliceStaticPos++}])")) { Span<char> setChars = stackalloc char[SetCharsSize]; // needs to be same size as detection check in caller int startingSliceStaticPos = sliceStaticPos; // Emit a case for each branch. for (int i = 0; i < childCount; i++) { sliceStaticPos = startingSliceStaticPos; RegexNode child = node.Child(i); Debug.Assert(child.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set or RegexNodeKind.Concatenate, DescribeNode(child, analysis)); Debug.Assert(child.Kind is not RegexNodeKind.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set)); RegexNode? childStart = child.FindBranchOneMultiOrSetStart(); Debug.Assert(childStart is not null, "Unexpectedly couldn't find the branch starting node."); Debug.Assert((childStart.Options & RegexOptions.IgnoreCase) == 0, "Expected only to find non-IgnoreCase branch starts"); if (childStart.Kind is RegexNodeKind.Set) { int numChars = RegexCharClass.GetSetChars(childStart.Str!, setChars); Debug.Assert(numChars != 0); writer.WriteLine($"case {string.Join(" or ", setChars.Slice(0, numChars).ToArray().Select(c => Literal(c)))}:"); } else { writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); } writer.Indent++; // Emit the code for the branch, without the first character that was already matched in the switch. switch (child.Kind) { case RegexNodeKind.Multi: EmitNode(CloneMultiWithoutFirstChar(child)); writer.WriteLine(); break; case RegexNodeKind.Concatenate: var newConcat = new RegexNode(RegexNodeKind.Concatenate, child.Options); if (childStart.Kind == RegexNodeKind.Multi) { newConcat.AddChild(CloneMultiWithoutFirstChar(childStart)); } int concatChildCount = child.ChildCount(); for (int j = 1; j < concatChildCount; j++) { newConcat.AddChild(child.Child(j)); } EmitNode(newConcat.Reduce()); writer.WriteLine(); break; static RegexNode CloneMultiWithoutFirstChar(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Multi); Debug.Assert(node.Str!.Length >= 2); return node.Str!.Length == 2 ? new RegexNode(RegexNodeKind.One, node.Options, node.Str![1]) : new RegexNode(RegexNodeKind.Multi, node.Options, node.Str!.Substring(1)); } } // This is only ever used for atomic alternations, so we can simply reset the doneLabel // after emitting the child, as nothing will backtrack here (and we need to reset it // so that all branches see the original). doneLabel = originalDoneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); writer.WriteLine($"break;"); writer.WriteLine(); writer.Indent--; } // Default branch if the character didn't match the start of any branches. CaseGoto("default:", doneLabel); } } void EmitAllBranches() { // Label to jump to when any branch completes successfully. string matchLabel = ReserveName("AlternationMatch"); // Save off pos. We'll need to reset this each time a branch fails. string startingPos = ReserveName("alternation_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. string? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { startingCapturePos = ReserveName("alternation_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } writer.WriteLine(); // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new string[childCount]; string backtrackLabel = ReserveName("AlternationBacktrack"); for (int i = 0; i < childCount; i++) { // If the alternation isn't atomic, backtracking may require our jump table jumping back // into these branches, so we can't use actual scopes, as that would hide the labels. using (EmitScope(writer, $"Branch {i}", faux: !isAtomic)) { bool isLastBranch = i == childCount - 1; string? nextBranch = null; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = ReserveName("AlternationBranch"); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); writer.WriteLine(); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { EmitStackPush(startingCapturePos is not null ? new[] { i.ToString(), startingPos, startingCapturePos } : new[] { i.ToString(), startingPos }); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); if (!isLastBranch || !isAtomic) { // If this isn't the last branch, we're about to output a reset section, // and if this isn't atomic, there will be a backtracking section before // the end of the method. In both of those cases, we've successfully // matched and need to skip over that code. If, however, this is the // last branch and this is an atomic alternation, we can just fall // through to the successfully matched location. Goto(matchLabel); } // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { writer.WriteLine(); MarkLabel(nextBranch!, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } writer.WriteLine(); } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel, emitSemicolon: false); EmitStackPop(startingCapturePos is not null ? new[] { startingCapturePos, startingPos } : new[] { startingPos}); using (EmitBlock(writer, $"switch ({StackPop()})")) { for (int i = 0; i < labelMap.Length; i++) { CaseGoto($"case {i}:", labelMap[i]); } } writer.WriteLine(); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); if (sliceStaticPos > 0) { TransferSliceStaticPosToPos(); writer.WriteLine(); } // If the specified capture hasn't yet captured anything, fail to match... except when using RegexOptions.ECMAScript, // in which case per ECMA 262 section 21.2.2.9 the backreference should succeed. if ((node.Options & RegexOptions.ECMAScript) != 0) { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { EmitWhenHasCapture(); } } else { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference doesn't match."); using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(doneLabel); } writer.WriteLine(); EmitWhenHasCapture(); } void EmitWhenHasCapture() { writer.WriteLine("// Get the captured text. If it doesn't match at the current position, the backreference doesn't match."); additionalDeclarations.Add("int matchLength = 0;"); writer.WriteLine($"matchLength = base.MatchLength({capnum});"); if (!IsCaseInsensitive(node)) { // If we're case-sensitive, we can simply validate that the remaining length of the slice is sufficient // to possibly match, and then do a SequenceEqual against the matched text. writer.WriteLine($"if ({sliceSpan}.Length < matchLength || "); using (EmitBlock(writer, $" !global::System.MemoryExtensions.SequenceEqual(inputSpan.Slice(base.MatchIndex({capnum}), matchLength), {sliceSpan}.Slice(0, matchLength)))")) { Goto(doneLabel); } } else { // For case-insensitive, we have to walk each character individually. using (EmitBlock(writer, $"if ({sliceSpan}.Length < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"inputSpan[matchIndex + i]")} != {ToLower(hasTextInfo, options, $"{sliceSpan}[i]")})")) { Goto(doneLabel); } } } writer.WriteLine(); writer.WriteLine($"pos += matchLength;"); SliceInputSpan(writer); } } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; // If the child branches might backtrack, we can't emit the branches inside constructs that // require braces, e.g. if/else, even though that would yield more idiomatic output. // But if we know for certain they won't backtrack, we can output the nicer code. if (analysis.IsAtomicByAncestor(node) || (!analysis.MayBacktrack(yesBranch) && (noBranch is null || !analysis.MayBacktrack(noBranch)))) { using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { writer.WriteLine($"// The {DescribeCapture(node.M, analysis)} captured a value. Match the first branch."); EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } if (noBranch is not null) { using (EmitBlock(writer, $"else")) { writer.WriteLine($"// Otherwise, match the second branch."); EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } } doneLabel = originalDoneLabel; // atomicity return; } string refNotMatched = ReserveName("ConditionalBackreferenceNotMatched"); string endConditional = ReserveName("ConditionalBackreferenceEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalbackreference_branch"); writer.WriteLine($"int {resumeAt} = 0;"); // While it would be nicely readable to use an if/else block, if the branches contain // anything that triggers backtracking, labels will end up being defined, and if they're // inside the scope block for the if or else, that will prevent jumping to them from // elsewhere. So we implement the if/else with labels and gotos manually. // Check to see if the specified capture number was captured. using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(refNotMatched); } writer.WriteLine(); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { Goto(endConditional); writer.WriteLine(); } MarkLabel(refNotMatched); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. bool hasBacktracking = postYesDoneLabel != originalDoneLabel || postNoDoneLabel != originalDoneLabel; if (hasBacktracking) { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); // Backtrack section string backtrack = ReserveName("ConditionalBackreferenceBacktrack"); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } } if (needsEndConditional) { MarkLabel(endConditional); } if (hasBacktracking) { // We're not atomic and at least one of the yes or no branches contained backtracking constructs, // so finish outputting our backtracking logic, which involves pushing onto the stack which // branch to backtrack into. EmitStackPush(resumeAt); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookahead. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; string expressionNotMatched = ReserveName("ConditionalExpressionNotMatched"); string endConditional = ReserveName("ConditionalExpressionEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalexpression_branch"); if (!isAtomic) { writer.WriteLine($"int {resumeAt} = 0;"); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. string? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { startingCapturePos = ReserveName("conditionalexpression_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookahead; however, a positive lookahead only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("conditionalexpression_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. writer.WriteLine("// Condition:"); EmitNode(condition); writer.WriteLine(); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. writer.WriteLine("// Condition matched:"); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; writer.WriteLine(); // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } Goto(endConditional); writer.WriteLine(); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. writer.WriteLine("// Condition did not match:"); MarkLabel(expressionNotMatched, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } writer.WriteLine(); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); string backtrack = ReserveName("ConditionalExpressionBacktrack"); doneLabel = backtrack; MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } MarkLabel(endConditional, emitSemicolon: false); EmitStackPush(resumeAt); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, rm.Tree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); TransferSliceStaticPosToPos(); string startingPos = ReserveName("capture_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); RegexNode child = node.Child(0); if (uncapnum != -1) { using (EmitBlock(writer, $"if (!base.IsMatched({uncapnum}))")) { Goto(doneLabel); } writer.WriteLine(); } // Emit child node. string originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; writer.WriteLine(); TransferSliceStaticPosToPos(); if (uncapnum == -1) { writer.WriteLine($"base.Capture({capnum}, {startingPos}, pos);"); } else { writer.WriteLine($"base.TransferCapture({capnum}, {uncapnum}, {startingPos}, pos);"); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. writer.WriteLine(); EmitStackPush(startingPos); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"CaptureBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(startingPos); if (!childBacktracks) { writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } // Emits the code to handle a positive lookahead assertion. void EmitPositiveLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("positivelookahead_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. writer.WriteLine(); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; } // Emits the code to handle a negative lookahead assertion. void EmitNegativeLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); string originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("negativelookahead_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; string negativeLookaheadDoneLabel = ReserveName("NegativeLookaheadMatch"); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookahead, which actually // means failure for a _negative_ lookahead, so we need to jump to the original done. writer.WriteLine(); Goto(originalDoneLabel); writer.WriteLine(); // Failures (success for a negative lookahead) jump here. MarkLabel(negativeLookaheadDoneLabel, emitSemicolon: false); // After the child completes in failure (success for negative lookahead), reset the text positions. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } // Separate out several node types that, for conciseness, don't need a header and scope written into the source. switch (node.Kind) { // Nothing is written for an empty case RegexNodeKind.Empty: return; // A match failure doesn't need a scope. case RegexNodeKind.Nothing: Goto(doneLabel); return; // Skip atomic nodes that wrap non-backtracking children; in such a case there's nothing to be made atomic. case RegexNodeKind.Atomic when !analysis.MayBacktrack(node.Child(0)): EmitNode(node.Child(0)); return; // Concatenate is a simplification in the node tree so that a series of children can be represented as one. // We don't need its presence visible in the source. case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); return; } // Put the node's code into its own scope. If the node contains labels that may need to // be visible outside of its scope, the scope is still emitted for clarity but is commented out. using (EmitScope(writer, DescribeNode(node, analysis), faux: analysis.MayBacktrack(node))) { switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Atomic when analysis.MayBacktrack(node.Child(0)): EmitAtomic(node, subsequent); return; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaheadAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaheadAssertion(node); break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(analysis.MayBacktrack(node.Child(0)), "Expected child to potentially backtrack"); // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. string originalDoneLabel = doneLabel; additionalDeclarations.Add("int stackpos = 0;"); string startingStackpos = ReserveName("atomic_stackpos"); writer.WriteLine($"int {startingStackpos} = stackpos;"); writer.WriteLine(); // Emit the child. EmitNode(node.Child(0), subsequent); writer.WriteLine(); // Reset the stack position and done label. writer.WriteLine($"stackpos = {startingStackpos};"); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); TransferSliceStaticPosToPos(); using (EmitBlock(writer, "if (base.runtextpos < pos)")) { writer.WriteLine("base.runtextpos = pos;"); } } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. string? prevDescription = null; int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. We also want to minimize the repetition of if blocks, // and so we try to emit a series of clauses all part of the same if block rather than one if block per child. if (emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { bool wroteClauses = true; writer.Write($"if ({SpanLengthCheck(requiredLength)}"); while (i < exclusiveEnd) { for (; i < exclusiveEnd; i++) { void WriteSingleCharChild(RegexNode child, bool includeDescription = true) { if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $" || // {prevDescription}" : " ||"); writer.Write(" "); } else { writer.Write("if ("); } EmitSingleChar(child, emitLengthCheck: false, clauseOnly: true); prevDescription = includeDescription ? DescribeNode(child, analysis) : null; wroteClauses = true; } RegexNode child = node.Child(i); if (child.Kind is RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set) { WriteSingleCharChild(child); } else if (child.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic && child.M == child.N && child.M <= MaxUnrollSize) { for (int c = 0; c < child.M; c++) { WriteSingleCharChild(child, includeDescription: c == 0); } } else { break; } } if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $") // {prevDescription}" : ")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } if (i < childCount) { writer.WriteLine(); } wroteClauses = false; prevDescription = null; } if (i < exclusiveEnd) { EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: false); if (i < childCount - 1) { writer.WriteLine(); } i++; } } i--; continue; } EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: emitLengthChecksIfRequired); if (i < childCount - 1) { writer.WriteLine(); } } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequentOrDefault(int index, RegexNode node, RegexNode? defaultNode) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return defaultNode; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, string? offset = null, bool clauseOnly = false) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); // This only emits a single check, but it's called from the looping constructs in a loop // to generate the code for a single check, so we map those looping constructs to the // appropriate single check. string expr = $"{sliceSpan}[{Sum(sliceStaticPos, offset)}]"; if (node.IsSetFamily) { expr = $"{MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: true, additionalDeclarations, ref requiredHelpers)}"; } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "!=" : "==")} {Literal(node.Ch)}"; } if (clauseOnly) { writer.Write(expr); } else { using (EmitBlock(writer, emitLengthCheck ? $"if ({SpanLengthCheck(1, offset)} || {expr})" : $"if ({expr})")) { Goto(doneLabel); } } sliceStaticPos++; } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); string call = node.Kind switch { RegexNodeKind.Boundary => "!IsBoundary", RegexNodeKind.NonBoundary => "IsBoundary", RegexNodeKind.ECMABoundary => "!IsECMABoundary", _ => "IsECMABoundary", }; RequiredHelperFunctions boundaryFunctionRequired = node.Kind switch { RegexNodeKind.Boundary or RegexNodeKind.NonBoundary => RequiredHelperFunctions.IsBoundary | RequiredHelperFunctions.IsWordChar, // IsBoundary internally uses IsWordChar _ => RequiredHelperFunctions.IsECMABoundary }; requiredHelpers |= boundaryFunctionRequired; using (EmitBlock(writer, $"if ({call}(inputSpan, pos{(sliceStaticPos > 0 ? $" + {sliceStaticPos}" : "")}))")) { Goto(doneLabel); } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. Goto(doneLabel); } else { using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != 0)" : "if (pos != base.runtextstart)")) { Goto(doneLabel); } } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { using (EmitBlock(writer, $"if ({sliceSpan}[{sliceStaticPos - 1}] != '\\n')")) { Goto(doneLabel); } } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the inputSpan field directly: using (EmitBlock(writer, $"if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { Goto(doneLabel); } } break; case RegexNodeKind.End: using (EmitBlock(writer, $"if ({IsSliceLengthGreaterThanSliceStaticPos()})")) { Goto(doneLabel); } break; case RegexNodeKind.EndZ: writer.WriteLine($"if ({sliceSpan}.Length > {sliceStaticPos + 1} || ({IsSliceLengthGreaterThanSliceStaticPos()} && {sliceSpan}[{sliceStaticPos}] != '\\n'))"); using (EmitBlock(writer, null)) { Goto(doneLabel); } break; case RegexNodeKind.Eol: using (EmitBlock(writer, $"if ({IsSliceLengthGreaterThanSliceStaticPos()} && {sliceSpan}[{sliceStaticPos}] != '\\n')")) { Goto(doneLabel); } break; string IsSliceLengthGreaterThanSliceStaticPos() => sliceStaticPos == 0 ? $"!{sliceSpan}.IsEmpty" : $"{sliceSpan}.Length > {sliceStaticPos}"; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); Debug.Assert(node.Str is not null); EmitMultiCharString(node.Str, IsCaseInsensitive(node), emitLengthCheck); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck) { Debug.Assert(str.Length >= 2); if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } using (EmitBlock(writer, $"for (int i = 0; i < {Literal(str)}.Length; i++)")) { string textSpanIndex = sliceStaticPos > 0 ? $"i + {sliceStaticPos}" : "i"; using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"{sliceSpan}[{textSpanIndex}]")} != {Literal(str)}[i])")) { Goto(doneLabel); } } } else { string sourceSpan = sliceStaticPos > 0 ? $"{sliceSpan}.Slice({sliceStaticPos})" : sliceSpan; using (EmitBlock(writer, $"if (!global::System.MemoryExtensions.StartsWith({sourceSpan}, {Literal(str)}))")) { Goto(doneLabel); } } sliceStaticPos += str.Length; } void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); string backtrackingLabel = ReserveName("CharLoopBacktrack"); string endLoop = ReserveName("CharLoopEnd"); string startingPos = ReserveName("charloop_starting_pos"); string endingPos = ReserveName("charloop_ending_pos"); additionalDeclarations.Add($"int {startingPos} = 0, {endingPos} = 0;"); // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); EmitSingleCharAtomicLoop(node); writer.WriteLine(); TransferSliceStaticPosToPos(); writer.WriteLine($"{endingPos} = pos;"); EmitAdd(writer, startingPos, node.M); Goto(endLoop); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel, emitSemicolon: false); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } EmitStackPop(endingPos, startingPos); writer.WriteLine(); if (subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { writer.WriteLine($"if ({startingPos} >= {endingPos} ||"); using (EmitBlock(writer, literal.Item2 is not null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, global::System.Math.Min(inputSpan.Length, {endingPos} + {literal.Item2.Length - 1}) - {startingPos}), {Literal(literal.Item2)})) < 0)" : literal.Item3 is null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item1)})) < 0)" : literal.Item3.Length switch { 2 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])})) < 0)", 3 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])}, {Literal(literal.Item3[2])})) < 0)", _ => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3)})) < 0)", })) { Goto(doneLabel); } writer.WriteLine($"{endingPos} += {startingPos};"); writer.WriteLine($"pos = {endingPos};"); } else { using (EmitBlock(writer, $"if ({startingPos} >= {endingPos})")) { Goto(doneLabel); } writer.WriteLine($"pos = --{endingPos};"); } SliceInputSpan(writer); writer.WriteLine(); MarkLabel(endLoop, emitSemicolon: false); EmitStackPush(expressionHasCaptures ? new[] { startingPos, endingPos, "base.Crawlpos()" } : new[] { startingPos, endingPos }); doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } if (node.M > 0) { // We emitted a repeater to handle the required iterations; add a newline after it. writer.WriteLine(); } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. string? iterationCount = null; string? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = $"{node.N - node.M}"; iterationCount = ReserveName("lazyloop_iteration"); writer.WriteLine($"int {iterationCount} = 0;"); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. string? capturePos = null; if (expressionHasCaptures) { capturePos = ReserveName("lazyloop_capturepos"); additionalDeclarations.Add($"int {capturePos} = 0;"); } // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. string startingPos = ReserveName("lazyloop_pos"); additionalDeclarations.Add($"int {startingPos} = 0;"); writer.WriteLine($"{startingPos} = pos;"); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. string endLoopLabel = ReserveName("LazyLoopEnd"); Goto(endLoopLabel); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here. string backtrackingLabel = ReserveName("LazyLoopBacktrack"); MarkLabel(backtrackingLabel, emitSemicolon: false); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturePos is not null) { EmitUncaptureUntil(capturePos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { using (EmitBlock(writer, $"if ({iterationCount} >= {maxIterations})")) { Goto(doneLabel); } writer.WriteLine($"{iterationCount}++;"); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). writer.WriteLine( literal.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item2[0])});" : literal.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item1)});" : literal.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch + literal.Item3)});", }); using (EmitBlock(writer, $"if ((uint){startingPos} >= (uint){sliceSpan}.Length || {sliceSpan}[{startingPos}] == {Literal(node.Ch)})")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. writer.WriteLine( literal2.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item2)});" : literal2.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item1)});" : literal2.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])});", 3 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])}, {Literal(literal2.Item3[2])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3)});", }); using (EmitBlock(writer, $"if ({startingPos} < 0)")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } // Store the position we've left off at in case we need to iterate again. writer.WriteLine($"{startingPos} = pos;"); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. string originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes writer.WriteLine(); MarkLabel(endLoopLabel); if (capturePos is not null) { writer.WriteLine($"{capturePos} = base.Crawlpos();"); } if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state var toPushPop = new List<string>(3) { startingPos }; if (capturePos is not null) { toPushPop.Add(capturePos); } if (iterationCount is not null) { toPushPop.Add(iterationCount); } string[] toPushPopArray = toPushPop.ToArray(); EmitStackPush(toPushPopArray); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("CharLazyBacktrack"); MarkLabel(backtrack, emitSemicolon: false); Array.Reverse(toPushPopArray); EmitStackPop(toPushPopArray); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; string originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } writer.WriteLine(); } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string startingPos = ReserveName("lazyloop_starting_pos"); string iterationCount = ReserveName("lazyloop_iteration"); string sawEmpty = ReserveName("lazyLoopEmptySeen"); string body = ReserveName("LazyLoopBody"); string endLoop = ReserveName("LazyLoopEnd"); writer.WriteLine($"int {iterationCount} = 0, {startingPos} = pos, {sawEmpty} = 0;"); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { Goto(endLoop); } writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos", sawEmpty } : new[] { startingPos, "pos", sawEmpty }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LazyLoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(body); } } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. using (EmitBlock(writer, $"if (pos == {startingPos})")) { writer.WriteLine($"{sawEmpty} = 1;"); } // We matched the next iteration. Jump to the subsequent code. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop(sawEmpty, "pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (doneLabel == originalDoneLabel) { Goto(originalDoneLabel); } else { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); } writer.WriteLine(); MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackPush(startingPos, iterationCount, sawEmpty); string skipBacktrack = ReserveName("SkipBacktrack"); Goto(skipBacktrack); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"LazyLoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(sawEmpty, iterationCount, startingPos); if (maxIterations == int.MaxValue) { using (EmitBlock(writer, $"if ({sawEmpty} == 0)")) { Goto(body); } } else { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, maxIterations)} && {sawEmpty} == 0)")) { Goto(body); } } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthCheck = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthCheck); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthCheck); return; } if (iterations <= MaxUnrollSize) { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length || // slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // { // goto doneLabel; // } writer.Write($"if ("); if (emitLengthCheck) { writer.WriteLine($"{SpanLengthCheck(iterations)} ||"); writer.Write(" "); } EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); for (int i = 1; i < iterations; i++) { writer.WriteLine(" ||"); writer.Write(" "); EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); } writer.WriteLine(")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } } else { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthCheck) { EmitSpanLengthCheck(iterations); } string repeaterSpan = "repeaterSlice"; // As this repeater doesn't wrap arbitrary node emits, this shouldn't conflict with anything writer.WriteLine($"global::System.ReadOnlySpan<char> {repeaterSpan} = {sliceSpan}.Slice({sliceStaticPos}, {iterations});"); using (EmitBlock(writer, $"for (int i = 0; i < {repeaterSpan}.Length; i++)")) { EmitTimeoutCheck(writer, hasTimeout); string tmpTextSpanLocal = sliceSpan; // we want EmitSingleChar to refer to this temporary int tmpSliceStaticPos = sliceStaticPos; sliceSpan = repeaterSpan; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: "i"); sliceSpan = tmpTextSpanLocal; sliceStaticPos = tmpSliceStaticPos; } sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; Span<char> setChars = stackalloc char[5]; // 5 is max optimized by IndexOfAny today int numSetChars = 0; string iterationLocal = ReserveName("iteration"); if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOf({sliceSpan}"); if (sliceStaticPos > 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine($", {Literal(node.Ch)});"); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it should // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}"); if (sliceStaticPos != 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine(numSetChars switch { 2 => $", {Literal(setChars[0])}, {Literal(setChars[1])});", 3 => $", {Literal(setChars[0])}, {Literal(setChars[1])}, {Literal(setChars[2])});", _ => $", {Literal(setChars.Slice(0, numSetChars).ToString())});", }); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. TransferSliceStaticPosToPos(); writer.WriteLine($"int {iterationLocal} = inputSpan.Length - pos;"); } else { // For everything else, do a normal loop. string expr = $"{sliceSpan}[{iterationLocal}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } if (minIterations != 0 || maxIterations != int.MaxValue) { // For any loops other than * loops, transfer text pos to pos in // order to zero it out to be able to use the single iteration variable // for both iteration count and indexer. TransferSliceStaticPosToPos(); } writer.WriteLine($"int {iterationLocal} = {sliceStaticPos};"); sliceStaticPos = 0; string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}(uint){iterationLocal} < (uint){sliceSpan}.Length && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } // Check to ensure we've found at least min iterations. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationLocal, minIterations)})")) { Goto(doneLabel); } writer.WriteLine(); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({iterationLocal});"); writer.WriteLine($"pos += {iterationLocal};"); } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); string expr = $"{sliceSpan}[{sliceStaticPos}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } string spaceAvailable = sliceStaticPos != 0 ? $"(uint){sliceSpan}.Length > (uint){sliceStaticPos}" : $"!{sliceSpan}.IsEmpty"; using (EmitBlock(writer, $"if ({spaceAvailable} && {expr})")) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice(1);"); writer.WriteLine($"pos++;"); } } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. string i = ReserveName("loop_iteration"); using (EmitBlock(writer, $"for (int {i} = 0; {i} < {node.M}; {i}++)")) { EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs } } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string originalDoneLabel = doneLabel; string startingPos = ReserveName("loop_starting_pos"); string iterationCount = ReserveName("loop_iteration"); string body = ReserveName("LoopBody"); string endLoop = ReserveName("LoopEnd"); additionalDeclarations.Add($"int {iterationCount} = 0, {startingPos} = 0;"); writer.WriteLine($"{iterationCount} = 0;"); writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos" } : new[] { startingPos, "pos" }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); writer.WriteLine(); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. using (EmitBlock(writer, (minIterations > 0, maxIterations == int.MaxValue) switch { (true, true) => $"if (pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)})", (true, false) => $"if ((pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)}) && {CountIsLessThan(iterationCount, maxIterations)})", (false, true) => $"if (pos != {startingPos})", (false, false) => $"if (pos != {startingPos} && {CountIsLessThan(iterationCount, maxIterations)})", })) { Goto(body); } // We've matched as many iterations as we can with this configuration. Jump to what comes after the loop. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop("pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (minIterations > 0) { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(childBacktracks ? doneLabel : originalDoneLabel); } } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { Goto(endLoop); writer.WriteLine(); string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state EmitStackPush(startingPos, iterationCount); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(iterationCount, startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } } // Gets a comparison for whether the value is less than the upper bound. static string CountIsLessThan(string value, int exclusiveUpper) => exclusiveUpper == 1 ? $"{value} == 0" : $"{value} < {exclusiveUpper}"; // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(string capturepos) { string name = "UncaptureUntil"; if (!additionalLocalFunctions.ContainsKey(name)) { var lines = new string[9]; lines[0] = "// <summary>Undo captures until we reach the specified capture position.</summary>"; lines[1] = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"void {name}(int capturepos)"; lines[3] = "{"; lines[4] = " while (base.Crawlpos() > capturepos)"; lines[5] = " {"; lines[6] = " base.Uncapture();"; lines[7] = " }"; lines[8] = "}"; additionalLocalFunctions.Add(name, lines); } writer.WriteLine($"{name}({capturepos});"); } /// <summary>Pushes values on to the backtracking stack.</summary> void EmitStackPush(params string[] args) { Debug.Assert(args.Length is >= 1); string function = $"StackPush{args.Length}"; additionalDeclarations.Add("int stackpos = 0;"); if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[24 + args.Length]; lines[0] = $"// <summary>Push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[3] = $"{{"; lines[4] = $" // If there's space available for {(args.Length > 1 ? $"all {args.Length} values, store them" : "the value, store it")}."; lines[5] = $" int[] s = stack;"; lines[6] = $" int p = pos;"; lines[7] = $" if ((uint){(args.Length > 1 ? $"(p + {args.Length - 1})" : "p")} < (uint)s.Length)"; lines[8] = $" {{"; for (int i = 0; i < args.Length; i++) { lines[9 + i] = $" s[p{(i == 0 ? "" : $" + {i}")}] = arg{i};"; } lines[9 + args.Length] = args.Length > 1 ? $" pos += {args.Length};" : " pos++;"; lines[10 + args.Length] = $" return;"; lines[11 + args.Length] = $" }}"; lines[12 + args.Length] = $""; lines[13 + args.Length] = $" // Otherwise, resize the stack to make room and try again."; lines[14 + args.Length] = $" WithResize(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[15 + args.Length] = $""; lines[16 + args.Length] = $" // <summary>Resize the backtracking stack array and push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the stack.</summary>"; lines[17 + args.Length] = $" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; lines[18 + args.Length] = $" static void WithResize(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[19 + args.Length] = $" {{"; lines[20 + args.Length] = $" global::System.Array.Resize(ref stack, (pos + {args.Length - 1}) * 2);"; lines[21 + args.Length] = $" {function}(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[22 + args.Length] = $" }}"; lines[23 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(ref base.runstack!, ref stackpos, {string.Join(", ", args)});"); } /// <summary>Pops values from the backtracking stack into the specified locations.</summary> void EmitStackPop(params string[] args) { Debug.Assert(args.Length is >= 1); if (args.Length == 1) { writer.WriteLine($"{args[0]} = {StackPop()};"); return; } string function = $"StackPop{args.Length}"; if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[5 + args.Length]; lines[0] = $"// <summary>Pop {args.Length} value{(args.Length == 1 ? "" : "s")} from the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(int[] stack, ref int pos{FormatN(", out int arg{0}", args.Length)})"; lines[3] = $"{{"; for (int i = 0; i < args.Length; i++) { lines[4 + i] = $" arg{i} = stack[--pos];"; } lines[4 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(base.runstack, ref stackpos, out {string.Join(", out ", args)});"); } /// <summary>Expression for popping the next item from the backtracking stack.</summary> string StackPop() => "base.runstack![--stackpos]"; /// <summary>Concatenates the strings resulting from formatting the format string with the values [0, count).</summary> static string FormatN(string format, int count) => string.Concat(from i in Enumerable.Range(0, count) select string.Format(format, i)); } private static bool EmitLoopTimeoutCounterIfNeeded(IndentedTextWriter writer, RegexMethod rm) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("int loopTimeoutCounter = 0;"); return true; } return false; } /// <summary>Emits a timeout check.</summary> private static void EmitTimeoutCheck(IndentedTextWriter writer, bool hasTimeout) { const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling. if (hasTimeout) { // Increment counter for each loop iteration. // Emit code to check the timeout every 2048th iteration. using (EmitBlock(writer, $"if (++loopTimeoutCounter == {LoopTimeoutCheckCount})")) { writer.WriteLine("loopTimeoutCounter = 0;"); writer.WriteLine("base.CheckTimeout();"); } writer.WriteLine(); } } private static bool EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(IndentedTextWriter writer, RegexMethod rm, AnalysisResults analysis) { if (analysis.HasIgnoreCase && ((RegexOptions)rm.Options & RegexOptions.CultureInvariant) == 0) { writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); return true; } return false; } private static bool UseToLowerInvariant(bool hasTextInfo, RegexOptions options) => !hasTextInfo || (options & RegexOptions.CultureInvariant) != 0; private static string ToLower(bool hasTextInfo, RegexOptions options, string expression) => UseToLowerInvariant(hasTextInfo, options) ? $"char.ToLowerInvariant({expression})" : $"textInfo.ToLower({expression})"; private static string ToLowerIfNeeded(bool hasTextInfo, RegexOptions options, string expression, bool toLower) => toLower ? ToLower(hasTextInfo, options, expression) : expression; private static string MatchCharacterClass(bool hasTextInfo, RegexOptions options, string chExpr, string charClass, bool caseInsensitive, bool negate, HashSet<string> additionalDeclarations, ref RequiredHelperFunctions requiredHelpers) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // ideally this could just be "return true;", but we need to evaluate the expression for its side effects return $"({chExpr} {(negate ? "<" : ">=")} 0)"; // a char is unsigned and thus won't ever be negative case RegexCharClass.DigitClass: case RegexCharClass.NotDigitClass: negate ^= charClass == RegexCharClass.NotDigitClass; return $"{(negate ? "!" : "")}char.IsDigit({chExpr})"; case RegexCharClass.SpaceClass: case RegexCharClass.NotSpaceClass: negate ^= charClass == RegexCharClass.NotSpaceClass; return $"{(negate ? "!" : "")}char.IsWhiteSpace({chExpr})"; case RegexCharClass.WordClass: case RegexCharClass.NotWordClass: requiredHelpers |= RequiredHelperFunctions.IsWordChar; negate ^= charClass == RegexCharClass.NotWordClass; return $"{(negate ? "!" : "")}IsWordChar({chExpr})"; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant(hasTextInfo, options); if (!invariant) { chExpr = ToLower(hasTextInfo, options, chExpr); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { negate ^= RegexCharClass.IsNegated(charClass); return lowInclusive == highInclusive ? $"({chExpr} {(negate ? "!=" : "==")} {Literal(lowInclusive)})" : $"(((uint){chExpr}) - {Literal(lowInclusive)} {(negate ? ">" : "<=")} (uint)({Literal(highInclusive)} - {Literal(lowInclusive)}))"; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { negate ^= negated; return $"(char.GetUnicodeCategory({chExpr}) {(negate ? "!=" : "==")} global::System.Globalization.UnicodeCategory.{category})"; } // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it may be cheaper and smaller to compare against each than it is to use a lookup table. We can also special-case // the very common case with case insensitivity of two characters next to each other being the upper and lowercase // ASCII variants of each other, in which case we can use bit manipulation to avoid a comparison. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int mask; switch (RegexCharClass.GetSetChars(charClass, setChars)) { case 2: if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) { return $"(({chExpr} | 0x{mask:X}) {(negate ? "!=" : "==")} {Literal((char)(setChars[1] | mask))})"; } additionalDeclarations.Add("char ch;"); return negate ? $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}))" : $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}))"; case 3: additionalDeclarations.Add("char ch;"); return (negate, RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) switch { (false, false) => $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}) | (ch == {Literal(setChars[2])}))", (true, false) => $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}) & (ch != {Literal(setChars[2])}))", (false, true) => $"((((ch = {chExpr}) | 0x{mask:X}) == {Literal((char)(setChars[1] | mask))}) | (ch == {Literal(setChars[2])}))", (true, true) => $"((((ch = {chExpr}) | 0x{mask:X}) != {Literal((char)(setChars[1] | mask))}) & (ch != {Literal(setChars[2])}))", }; } } // All options after this point require a ch local. additionalDeclarations.Add("char ch;"); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) return negate ? $"((ch = {chExpr}) < 128 || !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) >= 128 && global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. return negate ? $"((ch = {chExpr}) >= 128 && !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) < 128 || global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = StringExtensions.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. return negate ? $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. return negate ? $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. return (negate, invariant) switch { (false, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (true, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (false, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", (true, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", }; } /// <summary> /// Replaces <see cref="AdditionalDeclarationsPlaceholder"/> in <paramref name="writer"/> with /// all of the variable declarations in <paramref name="declarations"/>. /// </summary> /// <param name="writer">The writer around a StringWriter to have additional declarations inserted into.</param> /// <param name="declarations">The additional declarations to insert.</param> /// <param name="position">The position into the writer at which to insert the additional declarations.</param> /// <param name="indent">The indentation to use for the additional declarations.</param> private static void ReplaceAdditionalDeclarations(IndentedTextWriter writer, HashSet<string> declarations, int position, int indent) { if (declarations.Count != 0) { var tmp = new StringBuilder(); foreach (string decl in declarations.OrderBy(s => s)) { for (int i = 0; i < indent; i++) { tmp.Append(IndentedTextWriter.DefaultTabString); } tmp.AppendLine(decl); } ((StringWriter)writer.InnerWriter).GetStringBuilder().Insert(position, tmp.ToString()); } } /// <summary>Formats the character as valid C#.</summary> private static string Literal(char c) => SymbolDisplay.FormatLiteral(c, quote: true); /// <summary>Formats the string as valid C#.</summary> private static string Literal(string s) => SymbolDisplay.FormatLiteral(s, quote: true); private static string Literal(RegexOptions options) { string s = options.ToString(); if (int.TryParse(s, out _)) { // The options were formatted as an int, which means the runtime couldn't // produce a textual representation. So just output casting the value as an int. return $"(global::System.Text.RegularExpressions.RegexOptions)({(int)options})"; } // Parse the runtime-generated "Option1, Option2" into each piece and then concat // them back together. string[] parts = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { parts[i] = "global::System.Text.RegularExpressions.RegexOptions." + parts[i].Trim(); } return string.Join(" | ", parts); } /// <summary>Gets a textual description of the node fit for rendering in a comment in source.</summary> private static string DescribeNode(RegexNode node, AnalysisResults analysis) => node.Kind switch { RegexNodeKind.Alternate => $"Match with {node.ChildCount()} alternative expressions{(analysis.IsAtomicByAncestor(node) ? ", atomically" : "")}.", RegexNodeKind.Atomic => $"Atomic group.", RegexNodeKind.Beginning => "Match if at the beginning of the string.", RegexNodeKind.Bol => "Match if at the beginning of a line.", RegexNodeKind.Boundary => $"Match if at a word boundary.", RegexNodeKind.Capture when node.M == -1 && node.N != -1 => $"Non-capturing balancing group. Uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N != -1 => $"Balancing group. Captures the {DescribeCapture(node.M, analysis)} and uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N == -1 => $"{DescribeCapture(node.M, analysis)}.", RegexNodeKind.Concatenate => "Match a sequence of expressions.", RegexNodeKind.ECMABoundary => $"Match if at a word boundary (according to ECMAScript rules).", RegexNodeKind.Empty => $"Match an empty string.", RegexNodeKind.End => "Match if at the end of the string.", RegexNodeKind.EndZ => "Match if at the end of the string or if before an ending newline.", RegexNodeKind.Eol => "Match if at the end of a line.", RegexNodeKind.Loop or RegexNodeKind.Lazyloop => node.M == 0 && node.N == 1 ? $"Optional ({(node.Kind is RegexNodeKind.Loop ? "greedy" : "lazy")})." : $"Loop {DescribeLoop(node, analysis)}.", RegexNodeKind.Multi => $"Match the string {Literal(node.Str!)}.", RegexNodeKind.NonBoundary => $"Match if at anything other than a word boundary.", RegexNodeKind.NonECMABoundary => $"Match if at anything other than a word boundary (according to ECMAScript rules).", RegexNodeKind.Nothing => $"Fail to match.", RegexNodeKind.Notone => $"Match any character other than {Literal(node.Ch)}.", RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy => $"Match a character other than {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.One => $"Match {Literal(node.Ch)}.", RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.NegativeLookaround => $"Zero-width negative lookahead assertion.", RegexNodeKind.Backreference => $"Match the same text as matched by the {DescribeCapture(node.M, analysis)}.", RegexNodeKind.PositiveLookaround => $"Zero-width positive lookahead assertion.", RegexNodeKind.Set => $"Match {DescribeSet(node.Str!)}.", RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => $"Match {DescribeSet(node.Str!)} {DescribeLoop(node, analysis)}.", RegexNodeKind.Start => "Match if at the start position.", RegexNodeKind.ExpressionConditional => $"Conditionally match one of two expressions depending on whether an initial expression matches.", RegexNodeKind.BackreferenceConditional => $"Conditionally match one of two expressions depending on whether the {DescribeCapture(node.M, analysis)} matched.", RegexNodeKind.UpdateBumpalong => $"Advance the next matching position.", _ => $"Unknown node type {node.Kind}", }; /// <summary>Gets an identifer to describe a capture group.</summary> private static string DescribeCapture(int capNum, AnalysisResults analysis) { // If we can get a capture name from the captures collection and it's not just a numerical representation of the group, use it. string name = RegexParser.GroupNameFromNumber(analysis.RegexTree.CaptureNumberSparseMapping, analysis.RegexTree.CaptureNames, analysis.RegexTree.CaptureCount, capNum); if (!string.IsNullOrEmpty(name) && (!int.TryParse(name, out int id) || id != capNum)) { name = Literal(name); } else { // Otherwise, create a numerical description of the capture group. int tens = capNum % 10; name = tens is >= 1 and <= 3 && capNum % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 tens switch { 1 => $"{capNum}st", 2 => $"{capNum}nd", _ => $"{capNum}rd", } : $"{capNum}th"; } return $"{name} capture group"; } /// <summary>Gets a textual description of what characters match a set.</summary> private static string DescribeSet(string charClass) => charClass switch { RegexCharClass.AnyClass => "any character", RegexCharClass.DigitClass => "a Unicode digit", RegexCharClass.ECMADigitClass => "'0' through '9'", RegexCharClass.ECMASpaceClass => "a whitespace character (ECMA)", RegexCharClass.ECMAWordClass => "a word character (ECMA)", RegexCharClass.NotDigitClass => "any character other than a Unicode digit", RegexCharClass.NotECMADigitClass => "any character other than '0' through '9'", RegexCharClass.NotECMASpaceClass => "any character other than a space character (ECMA)", RegexCharClass.NotECMAWordClass => "any character other than a word character (ECMA)", RegexCharClass.NotSpaceClass => "any character other than a space character", RegexCharClass.NotWordClass => "any character other than a word character", RegexCharClass.SpaceClass => "a whitespace character", RegexCharClass.WordClass => "a word character", _ => $"a character in the set {RegexCharClass.DescribeSet(charClass)}", }; /// <summary>Writes a textual description of the node tree fit for rending in source.</summary> /// <param name="writer">The writer to which the description should be written.</param> /// <param name="node">The node being written.</param> /// <param name="prefix">The prefix to write at the beginning of every line, including a "//" for a comment.</param> /// <param name="analyses">Analysis of the tree</param> /// <param name="depth">The depth of the current node.</param> private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, AnalysisResults analysis, int depth = 0) { bool skip = node.Kind switch { // For concatenations, flatten the contents into the parent, but only if the parent isn't a form of alternation, // where each branch is considered to be independent rather than a concatenation. RegexNodeKind.Concatenate when node.Parent is not { Kind: RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional } => true, // For atomic, skip the node if we'll instead render the atomic label as part of rendering the child. RegexNodeKind.Atomic when node.Child(0).Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop or RegexNodeKind.Alternate => true, // Don't skip anything else. _ => false, }; if (!skip) { string tag = node.Parent?.Kind switch { RegexNodeKind.ExpressionConditional when node.Parent.Child(0) == node => "Condition: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(1) == node => "Matched: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(2) == node => "Not Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(0) == node => "Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(1) == node => "Not Matched: ", _ => "", }; // Write out the line for the node. const char BulletPoint = '\u25CB'; writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node, analysis)}"); } // Recur into each of its children. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { int childDepth = skip ? depth : depth + 1; DescribeExpression(writer, node.Child(i), prefix, analysis, childDepth); } } /// <summary>Gets a textual description of a loop's style and bounds.</summary> private static string DescribeLoop(RegexNode node, AnalysisResults analysis) { string style = node.Kind switch { _ when node.M == node.N => "exactly", RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic => "atomically", RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop => "greedily", RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy => "lazily", RegexNodeKind.Loop => analysis.IsAtomicByAncestor(node) ? "greedily and atomically" : "greedily", _ /* RegexNodeKind.Lazyloop */ => analysis.IsAtomicByAncestor(node) ? "lazily and atomically" : "lazily", }; string bounds = node.M == node.N ? $" {node.M} times" : (node.M, node.N) switch { (0, int.MaxValue) => " any number of times", (1, int.MaxValue) => " at least once", (2, int.MaxValue) => " at least twice", (_, int.MaxValue) => $" at least {node.M} times", (0, 1) => ", optionally", (0, _) => $" at most {node.N} times", _ => $" at least {node.M} and at most {node.N} times" }; return style + bounds; } private static FinishEmitScope EmitScope(IndentedTextWriter writer, string title, bool faux = false) => EmitBlock(writer, $"// {title}", faux: faux); private static FinishEmitScope EmitBlock(IndentedTextWriter writer, string? clause, bool faux = false) { if (clause is not null) { writer.WriteLine(clause); } writer.WriteLine(faux ? "//{" : "{"); writer.Indent++; return new FinishEmitScope(writer, faux); } private static void EmitAdd(IndentedTextWriter writer, string variable, int value) { if (value == 0) { return; } writer.WriteLine( value == 1 ? $"{variable}++;" : value == -1 ? $"{variable}--;" : value > 0 ? $"{variable} += {value};" : value < 0 && value > int.MinValue ? $"{variable} -= {-value};" : $"{variable} += {value.ToString(CultureInfo.InvariantCulture)};"); } private readonly struct FinishEmitScope : IDisposable { private readonly IndentedTextWriter _writer; private readonly bool _faux; public FinishEmitScope(IndentedTextWriter writer, bool faux) { _writer = writer; _faux = faux; } public void Dispose() { if (_writer is not null) { _writer.Indent--; _writer.WriteLine(_faux ? "//}" : "}"); } } } /// <summary>Bit flags indicating which additional helpers should be emitted into the regex class.</summary> [Flags] private enum RequiredHelperFunctions { /// <summary>No additional functions are required.</summary> None = 0b0, /// <summary>The IsWordChar helper is required.</summary> IsWordChar = 0b1, /// <summary>The IsBoundary helper is required.</summary> IsBoundary = 0b10, /// <summary>The IsECMABoundary helper is required.</summary> IsECMABoundary = 0b100 } } }
1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions { /// <summary> /// RegexCompiler translates a block of RegexCode to MSIL, and creates a subclass of the RegexRunner type. /// </summary> internal abstract class RegexCompiler { private static readonly FieldInfo s_runtextstartField = RegexRunnerField("runtextstart"); private static readonly FieldInfo s_runtextposField = RegexRunnerField("runtextpos"); private static readonly FieldInfo s_runstackField = RegexRunnerField("runstack"); private static readonly MethodInfo s_captureMethod = RegexRunnerMethod("Capture"); private static readonly MethodInfo s_transferCaptureMethod = RegexRunnerMethod("TransferCapture"); private static readonly MethodInfo s_uncaptureMethod = RegexRunnerMethod("Uncapture"); private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched"); private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength"); private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex"); private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_isWordCharMethod = RegexRunnerMethod("IsWordChar"); private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos"); private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass"); private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout"); private static readonly MethodInfo s_charIsDigitMethod = typeof(char).GetMethod("IsDigit", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charIsWhiteSpaceMethod = typeof(char).GetMethod("IsWhiteSpace", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charGetUnicodeInfo = typeof(char).GetMethod("GetUnicodeCategory", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charToLowerInvariantMethod = typeof(char).GetMethod("ToLowerInvariant", new Type[] { typeof(char) })!; private static readonly MethodInfo s_cultureInfoGetCurrentCultureMethod = typeof(CultureInfo).GetMethod("get_CurrentCulture")!; private static readonly MethodInfo s_cultureInfoGetTextInfoMethod = typeof(CultureInfo).GetMethod("get_TextInfo")!; private static readonly MethodInfo s_spanGetItemMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Item", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanGetLengthMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Length")!; private static readonly MethodInfo s_memoryMarshalGetReference = typeof(MemoryMarshal).GetMethod("GetReference", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfChar = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfSpan = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!; private static readonly MethodInfo s_spanStartsWith = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_stringAsSpanMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string) })!; private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!; private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!; private static readonly MethodInfo s_arrayResize = typeof(Array).GetMethod("Resize")!.MakeGenericMethod(typeof(int)); private static readonly MethodInfo s_mathMinIntInt = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) })!; /// <summary>The ILGenerator currently in use.</summary> protected ILGenerator? _ilg; /// <summary>The options for the expression.</summary> protected RegexOptions _options; /// <summary>The <see cref="RegexTree"/> written for the expression.</summary> protected RegexTree? _regexTree; /// <summary>Whether this expression has a non-infinite timeout.</summary> protected bool _hasTimeout; /// <summary>Pool of Int32 LocalBuilders.</summary> private Stack<LocalBuilder>? _int32LocalsPool; /// <summary>Pool of ReadOnlySpan of char locals.</summary> private Stack<LocalBuilder>? _readOnlySpanCharLocalsPool; /// <summary>Local representing a cached TextInfo for the culture to use for all case-insensitive operations.</summary> private LocalBuilder? _textInfo; /// <summary>Local representing a timeout counter for loops (set loops and node loops).</summary> private LocalBuilder? _loopTimeoutCounter; /// <summary>A frequency with which the timeout should be validated.</summary> private const int LoopTimeoutCheckCount = 2048; private static FieldInfo RegexRunnerField(string fieldname) => typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; private static MethodInfo RegexRunnerMethod(string methname) => typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; /// <summary> /// Entry point to dynamically compile a regular expression. The expression is compiled to /// an in-memory assembly. /// </summary> internal static RegexRunnerFactory? Compile(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) => new RegexLWCGCompiler().FactoryInstanceFromCode(pattern, regexTree, options, hasTimeout); /// <summary>A macro for _ilg.DefineLabel</summary> private Label DefineLabel() => _ilg!.DefineLabel(); /// <summary>A macro for _ilg.MarkLabel</summary> private void MarkLabel(Label l) => _ilg!.MarkLabel(l); /// <summary>A macro for _ilg.Emit(Opcodes.Ldstr, str)</summary> protected void Ldstr(string str) => _ilg!.Emit(OpCodes.Ldstr, str); /// <summary>A macro for the various forms of Ldc.</summary> protected void Ldc(int i) => _ilg!.Emit(OpCodes.Ldc_I4, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ldc_I8).</summary> protected void LdcI8(long i) => _ilg!.Emit(OpCodes.Ldc_I8, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ret).</summary> protected void Ret() => _ilg!.Emit(OpCodes.Ret); /// <summary>A macro for _ilg.Emit(OpCodes.Dup).</summary> protected void Dup() => _ilg!.Emit(OpCodes.Dup); /// <summary>A macro for _ilg.Emit(OpCodes.Rem_Un).</summary> private void RemUn() => _ilg!.Emit(OpCodes.Rem_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Ceq).</summary> private void Ceq() => _ilg!.Emit(OpCodes.Ceq); /// <summary>A macro for _ilg.Emit(OpCodes.Cgt_Un).</summary> private void CgtUn() => _ilg!.Emit(OpCodes.Cgt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Clt_Un).</summary> private void CltUn() => _ilg!.Emit(OpCodes.Clt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Pop).</summary> private void Pop() => _ilg!.Emit(OpCodes.Pop); /// <summary>A macro for _ilg.Emit(OpCodes.Add).</summary> private void Add() => _ilg!.Emit(OpCodes.Add); /// <summary>A macro for _ilg.Emit(OpCodes.Sub).</summary> private void Sub() => _ilg!.Emit(OpCodes.Sub); /// <summary>A macro for _ilg.Emit(OpCodes.Mul).</summary> private void Mul() => _ilg!.Emit(OpCodes.Mul); /// <summary>A macro for _ilg.Emit(OpCodes.And).</summary> private void And() => _ilg!.Emit(OpCodes.And); /// <summary>A macro for _ilg.Emit(OpCodes.Or).</summary> private void Or() => _ilg!.Emit(OpCodes.Or); /// <summary>A macro for _ilg.Emit(OpCodes.Shl).</summary> private void Shl() => _ilg!.Emit(OpCodes.Shl); /// <summary>A macro for _ilg.Emit(OpCodes.Shr).</summary> private void Shr() => _ilg!.Emit(OpCodes.Shr); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloca).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloca(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloca, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_U2).</summary> private void LdindU2() => _ilg!.Emit(OpCodes.Ldind_U2); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I4).</summary> private void LdindI4() => _ilg!.Emit(OpCodes.Ldind_I4); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I8).</summary> private void LdindI8() => _ilg!.Emit(OpCodes.Ldind_I8); /// <summary>A macro for _ilg.Emit(OpCodes.Unaligned).</summary> private void Unaligned(byte alignment) => _ilg!.Emit(OpCodes.Unaligned, alignment); /// <summary>A macro for _ilg.Emit(OpCodes.Stloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Stloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Stloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldarg_0).</summary> protected void Ldthis() => _ilg!.Emit(OpCodes.Ldarg_0); /// <summary>A macro for _ilgEmit(OpCodes.Ldarg_1) </summary> private void Ldarg_1() => _ilg!.Emit(OpCodes.Ldarg_1); /// <summary>A macro for Ldthis(); Ldfld();</summary> protected void Ldthisfld(FieldInfo ft) { Ldthis(); _ilg!.Emit(OpCodes.Ldfld, ft); } /// <summary>Fetches the address of argument in passed in <paramref name="position"/></summary> /// <param name="position">The position of the argument which address needs to be fetched.</param> private void Ldarga_s(int position) => _ilg!.Emit(OpCodes.Ldarga_S, position); /// <summary>A macro for Ldthis(); Ldfld(); Stloc();</summary> private void Mvfldloc(FieldInfo ft, LocalBuilder lt) { Ldthisfld(ft); Stloc(lt); } /// <summary>A macro for _ilg.Emit(OpCodes.Stfld).</summary> protected void Stfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Stfld, ft); /// <summary>A macro for _ilg.Emit(OpCodes.Callvirt, mt).</summary> protected void Callvirt(MethodInfo mt) => _ilg!.Emit(OpCodes.Callvirt, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Call, mt).</summary> protected void Call(MethodInfo mt) => _ilg!.Emit(OpCodes.Call, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (long form).</summary> private void BrfalseFar(Label l) => _ilg!.Emit(OpCodes.Brfalse, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue) (long form).</summary> private void BrtrueFar(Label l) => _ilg!.Emit(OpCodes.Brtrue, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br) (long form).</summary> private void BrFar(Label l) => _ilg!.Emit(OpCodes.Br, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble) (long form).</summary> private void BleFar(Label l) => _ilg!.Emit(OpCodes.Ble, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt) (long form).</summary> private void BltFar(Label l) => _ilg!.Emit(OpCodes.Blt, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_Un) (long form).</summary> private void BltUnFar(Label l) => _ilg!.Emit(OpCodes.Blt_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge) (long form).</summary> private void BgeFar(Label l) => _ilg!.Emit(OpCodes.Bge, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un) (long form).</summary> private void BgeUnFar(Label l) => _ilg!.Emit(OpCodes.Bge_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne) (long form).</summary> private void BneFar(Label l) => _ilg!.Emit(OpCodes.Bne_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq) (long form).</summary> private void BeqFar(Label l) => _ilg!.Emit(OpCodes.Beq, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue_S) (short jump).</summary> private void Brtrue(Label l) => _ilg!.Emit(OpCodes.Brtrue_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br_S) (short jump).</summary> private void Br(Label l) => _ilg!.Emit(OpCodes.Br_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble_S) (short jump).</summary> private void Ble(Label l) => _ilg!.Emit(OpCodes.Ble_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_S) (short jump).</summary> private void Blt(Label l) => _ilg!.Emit(OpCodes.Blt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_S) (short jump).</summary> private void Bge(Label l) => _ilg!.Emit(OpCodes.Bge_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un_S) (short jump).</summary> private void BgeUn(Label l) => _ilg!.Emit(OpCodes.Bge_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump).</summary> private void Bgt(Label l) => _ilg!.Emit(OpCodes.Bgt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne_S) (short jump).</summary> private void Bne(Label l) => _ilg!.Emit(OpCodes.Bne_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq_S) (short jump).</summary> private void Beq(Label l) => _ilg!.Emit(OpCodes.Beq_S, l); /// <summary>A macro for the Ldlen instruction.</summary> private void Ldlen() => _ilg!.Emit(OpCodes.Ldlen); /// <summary>A macro for the Ldelem_I4 instruction.</summary> private void LdelemI4() => _ilg!.Emit(OpCodes.Ldelem_I4); /// <summary>A macro for the Stelem_I4 instruction.</summary> private void StelemI4() => _ilg!.Emit(OpCodes.Stelem_I4); private void Switch(Label[] table) => _ilg!.Emit(OpCodes.Switch, table); /// <summary>Declares a local bool.</summary> private LocalBuilder DeclareBool() => _ilg!.DeclareLocal(typeof(bool)); /// <summary>Declares a local int.</summary> private LocalBuilder DeclareInt32() => _ilg!.DeclareLocal(typeof(int)); /// <summary>Declares a local CultureInfo.</summary> private LocalBuilder? DeclareTextInfo() => _ilg!.DeclareLocal(typeof(TextInfo)); /// <summary>Declares a local string.</summary> private LocalBuilder DeclareString() => _ilg!.DeclareLocal(typeof(string)); private LocalBuilder DeclareReadOnlySpanChar() => _ilg!.DeclareLocal(typeof(ReadOnlySpan<char>)); /// <summary>Rents an Int32 local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentInt32Local() => new RentedLocalBuilder( _int32LocalsPool ??= new Stack<LocalBuilder>(), _int32LocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareInt32()); /// <summary>Rents a ReadOnlySpan(char) local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentReadOnlySpanCharLocal() => new RentedLocalBuilder( _readOnlySpanCharLocalsPool ??= new Stack<LocalBuilder>(1), // capacity == 1 as we currently don't expect overlapping instances _readOnlySpanCharLocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareReadOnlySpanChar()); /// <summary>Returned a rented local to the pool.</summary> private struct RentedLocalBuilder : IDisposable { private readonly Stack<LocalBuilder> _pool; private readonly LocalBuilder _local; internal RentedLocalBuilder(Stack<LocalBuilder> pool, LocalBuilder local) { _local = local; _pool = pool; } public static implicit operator LocalBuilder(RentedLocalBuilder local) => local._local; public void Dispose() { Debug.Assert(_pool != null); Debug.Assert(_local != null); Debug.Assert(!_pool.Contains(_local)); _pool.Push(_local); this = default; } } /// <summary>Sets the culture local to CultureInfo.CurrentCulture.</summary> private void InitLocalCultureInfo() { Debug.Assert(_textInfo != null); Call(s_cultureInfoGetCurrentCultureMethod); Callvirt(s_cultureInfoGetTextInfoMethod); Stloc(_textInfo); } /// <summary>Whether ToLower operations should be performed with the invariant culture as opposed to the one in <see cref="_textInfo"/>.</summary> private bool UseToLowerInvariant => _textInfo == null || (_options & RegexOptions.CultureInvariant) != 0; /// <summary>Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c).</summary> private void CallToLower() { if (UseToLowerInvariant) { Call(s_charToLowerInvariantMethod); } else { using RentedLocalBuilder currentCharLocal = RentInt32Local(); Stloc(currentCharLocal); Ldloc(_textInfo!); Ldloc(currentCharLocal); Callvirt(s_textInfoToLowerMethod); } } /// <summary>Generates the implementation for TryFindNextPossibleStartingPosition.</summary> protected void EmitTryFindNextPossibleStartingPosition() { Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder pos = DeclareInt32(); _textInfo = null; if ((_options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = _regexTree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when _regexTree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } // Load necessary locals // int pos = base.runtextpos; // ReadOnlySpan<char> inputSpan = dynamicMethodArg; // TODO: We can reference the arg directly rather than using another local. Mvfldloc(s_runtextposField, pos); Ldarg_1(); Stloc(inputSpan); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = _regexTree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); Label returnFalse = DefineLabel(); Label finishedLengthCheck = DefineLabel(); // if (pos > inputSpan.Length - _code.Tree.MinRequiredLength) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength > 0) { Ldc(minRequiredLength); Sub(); } Ble(finishedLengthCheck); MarkLabel(returnFalse); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); Ldc(0); Ret(); MarkLabel(finishedLengthCheck); // Emit any anchors. if (GenerateAnchors()) { return; } // Either anchors weren't specified, or they don't completely root all matches to a specific location. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {_regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: // return true; Ldc(1); Ret(); break; } // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool GenerateAnchors() { Label label; // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: label = DefineLabel(); Ldloc(pos); Ldc(0); Ble(label); Br(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: label = DefineLabel(); Ldloc(pos); Ldthisfld(s_runtextstartField); Ble(label); Br(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; } } // Now handle anchors that boost the position but don't determine immediate success or failure. switch (_regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: { // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any prefix or char class searches. label = DefineLabel(); // if (pos > 0... Ldloc(pos!); Ldc(0); Ble(label); // ... && inputSpan[pos - 1] != '\n') { ... } Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Beq(label); // int tmp = inputSpan.Slice(pos).IndexOf('\n'); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldc('\n'); Call(s_spanIndexOfChar); using (RentedLocalBuilder newlinePos = RentInt32Local()) { Stloc(newlinePos); // if (newlinePos < 0 || newlinePos + pos + 1 > inputSpan.Length) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(newlinePos); Ldc(0); Blt(returnFalse); Ldloc(newlinePos); Ldloc(pos); Add(); Ldc(1); Add(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bgt(returnFalse); // pos += newlinePos + 1; Ldloc(pos); Ldloc(newlinePos); Add(); Ldc(1); Add(); Stloc(pos); } MarkLabel(label); } break; } switch (_regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End or RegexNodeKind.EndZ when _regexTree.FindOptimizations.MaxPossibleLength is int maxLength: // Jump to the end, minus the max allowed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Bge(label); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Stloc(pos); MarkLabel(label); break; } } return false; } void EmitIndexOf_LeftToRight(string prefix) { using RentedLocalBuilder i = RentInt32Local(); // int i = inputSpan.Slice(pos).IndexOf(prefix); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); Stloc(i); // if (i < 0) goto ReturnFalse; Ldloc(i); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(i); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = _regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); using RentedLocalBuilder iLocal = RentInt32Local(); using RentedLocalBuilder textSpanLocal = RentReadOnlySpanCharLocal(); // ReadOnlySpan<char> span = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(textSpanLocal); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; Label checkSpanLengthLabel = default; Label charNotInClassLabel = default; Label loopBody = default; if (needLoop) { checkSpanLengthLabel = DefineLabel(); charNotInClassLabel = DefineLabel(); loopBody = DefineLabel(); // for (int i = 0; Ldc(0); Stloc(iLocal); BrFar(checkSpanLengthLabel); MarkLabel(loopBody); } if (canUseIndexOf) { setIndex = 1; if (needLoop) { // slice.Slice(iLocal + primarySet.Distance); Ldloca(textSpanLocal); Ldloc(iLocal); if (primarySet.Distance != 0) { Ldc(primarySet.Distance); Add(); } Call(s_spanSliceIntMethod); } else if (primarySet.Distance != 0) { // slice.Slice(primarySet.Distance) Ldloca(textSpanLocal); Ldc(primarySet.Distance); Call(s_spanSliceIntMethod); } else { // slice Ldloc(textSpanLocal); } switch (primarySet.Chars!.Length) { case 1: // tmp = ...IndexOf(setChars[0]); Ldc(primarySet.Chars[0]); Call(s_spanIndexOfChar); break; case 2: // tmp = ...IndexOfAny(setChars[0], setChars[1]); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: // tmp = ...IndexOfAny(setChars[0], setChars[1], setChars[2]}); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Ldc(primarySet.Chars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(primarySet.Chars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } if (needLoop) { // i += tmp; // if (tmp < 0) goto returnFalse; using (RentedLocalBuilder tmp = RentInt32Local()) { Stloc(tmp); Ldloc(iLocal); Ldloc(tmp); Add(); Stloc(iLocal); Ldloc(tmp); Ldc(0); BltFar(returnFalse); } } else { // i = tmp; // if (i < 0) goto returnFalse; Stloc(iLocal); Ldloc(iLocal); Ldc(0); BltFar(returnFalse); } // if (i >= slice.Length - (minRequiredLength - 1)) goto returnFalse; if (sets.Count > 1) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); Ldc(minRequiredLength - 1); Sub(); Ldloc(iLocal); BleFar(returnFalse); } } // if (!CharInClass(slice[i], prefix[0], "...")) continue; // if (!CharInClass(slice[i + 1], prefix[1], "...")) continue; // if (!CharInClass(slice[i + 2], prefix[2], "...")) continue; // ... Debug.Assert(setIndex is 0 or 1); for ( ; setIndex < sets.Count; setIndex++) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Ldloc(iLocal); if (sets[setIndex].Distance != 0) { Ldc(sets[setIndex].Distance); Add(); } Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(sets[setIndex].Set, sets[setIndex].CaseInsensitive); BrfalseFar(charNotInClassLabel); } // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(iLocal); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); if (needLoop) { MarkLabel(charNotInClassLabel); // for (...; ...; i++) Ldloc(iLocal); Ldc(1); Add(); Stloc(iLocal); // for (...; i < span.Length - (minRequiredLength - 1); ...); MarkLabel(checkSpanLengthLabel); Ldloc(iLocal); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); if (setsToUse > 1 || primarySet.Distance != 0) { Ldc(minRequiredLength - 1); Sub(); } BltFar(loopBody); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = _regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); // while (true) Label loopBody = DefineLabel(); Label loopEnd = DefineLabel(); MarkLabel(loopBody); // ReadOnlySpan<char> slice = inputSpan.Slice(pos); using RentedLocalBuilder slice = RentReadOnlySpanCharLocal(); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); // Find the literal. If we can't find it, we're done searching. // int i = slice.IndexOf(literal); // if (i < 0) break; using RentedLocalBuilder i = RentInt32Local(); Ldloc(slice); if (target.Literal.String is string literalString) { Ldstr(literalString); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (target.Literal.Chars is not char[] literalChars) { Ldc(target.Literal.Char); Call(s_spanIndexOfChar); } else { switch (literalChars.Length) { case 2: Ldc(literalChars[0]); Ldc(literalChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literalChars[0]); Ldc(literalChars[1]); Ldc(literalChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(literalChars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } Stloc(i); Ldloc(i); Ldc(0); BltFar(loopEnd); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. // int prev = i; using RentedLocalBuilder prev = RentInt32Local(); Ldloc(i); Stloc(prev); // while ((uint)--prev < (uint)slice.Length) && MatchCharClass(slice[prev])); Label innerLoopBody = DefineLabel(); Label innerLoopEnd = DefineLabel(); MarkLabel(innerLoopBody); Ldloc(prev); Ldc(1); Sub(); Stloc(prev); Ldloc(prev); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(innerLoopEnd); Ldloca(slice); Ldloc(prev); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(target.LoopNode.Str!, caseInsensitive: false); BrtrueFar(innerLoopBody); MarkLabel(innerLoopEnd); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. // if ((i - prev - 1) < target.LoopNode.M) // { // pos += i + 1; // continue; // } Label metMinimum = DefineLabel(); Ldloc(i); Ldloc(prev); Sub(); Ldc(1); Sub(); Ldc(target.LoopNode.M); Bge(metMinimum); Ldloc(pos); Ldloc(i); Add(); Ldc(1); Add(); Stloc(pos); BrFar(loopBody); MarkLabel(metMinimum); } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. // base.runtextpos = pos + prev + 1; // return true; Ldthis(); Ldloc(pos); Ldloc(prev); Add(); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); // } MarkLabel(loopEnd); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } /// <summary>Generates the implementation for TryMatchAtCurrentPosition.</summary> protected void EmitTryMatchAtCurrentPosition() { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); // Get the root Capture node of the tree. RegexNode node = _regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); // Skip the Capture node. We handle the implicit root capture specially. node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. // base.Capture(0, base.runtextpos, base.runtextpos + node.Str.Length); // base.runtextpos = base.runtextpos + node.Str.Length; // return true; Ldthis(); Dup(); Ldc(0); Ldthisfld(s_runtextposField); Dup(); Ldc(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1); Add(); Call(s_captureMethod); Ldthisfld(s_runtextposField); Ldc(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); return; // The source generator special-cases RegexNode.Empty, for purposes of code learning rather than // performance. Since that's not applicable to RegexCompiler, that code isn't mirrored here. } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(_regexTree); // Initialize the main locals used throughout the implementation. LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder originalPos = DeclareInt32(); LocalBuilder pos = DeclareInt32(); LocalBuilder slice = DeclareReadOnlySpanChar(); Label doneLabel = DefineLabel(); Label originalDoneLabel = doneLabel; if (_hasTimeout) { _loopTimeoutCounter = DeclareInt32(); } // CultureInfo culture = CultureInfo.CurrentCulture; // only if the whole expression or any subportion is ignoring case, and we're not using invariant InitializeCultureForTryMatchAtCurrentPositionIfNecessary(analysis); // ReadOnlySpan<char> inputSpan = input; Ldarg_1(); Stloc(inputSpan); // int pos = base.runtextpos; // int originalpos = pos; Ldthisfld(s_runtextposField); Stloc(pos); Ldloc(pos); Stloc(originalPos); // int stackpos = 0; LocalBuilder stackpos = DeclareInt32(); Ldc(0); Stloc(stackpos); // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(); // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // pos += sliceStaticPos; // base.runtextpos = pos; // Capture(0, originalpos, pos); // return true; Ldthis(); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); Stloc(pos); Ldloc(pos); } Stfld(s_runtextposField); Ldthis(); Ldc(0); Ldloc(originalPos); Ldloc(pos); Call(s_captureMethod); Ldc(1); Ret(); // NOTE: The following is a difference from the source generator. The source generator emits: // UncaptureUntil(0); // return false; // at every location where the all-up match is known to fail. In contrast, the compiler currently // emits this uncapture/return code in one place and jumps to it upon match failure. The difference // stems primarily from the return-at-each-location pattern resulting in cleaner / easier to read // source code, which is not an issue for RegexCompiler emitting IL instead of C#. // If the graph contained captures, undo any remaining to handle failed matches. if (expressionHasCaptures) { // while (base.Crawlpos() != 0) base.Uncapture(); Label finalReturnLabel = DefineLabel(); Br(finalReturnLabel); MarkLabel(originalDoneLabel); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Brtrue(body); // Done: MarkLabel(finalReturnLabel); } else { // Done: MarkLabel(originalDoneLabel); } // return false; Ldc(0); Ret(); // Generated code successfully. return; static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan() { // slice = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); } // Emits the sum of a constant and a value from a local. void EmitSum(int constant, LocalBuilder? local) { if (local == null) { Ldc(constant); } else if (constant == 0) { Ldloc(local); } else { Ldloc(local); Ldc(constant); Add(); } } // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, LocalBuilder? dynamicRequiredLength = null) { // if ((uint)(sliceStaticPos + requiredLength + dynamicRequiredLength - 1) >= (uint)slice.Length) goto Done; Debug.Assert(requiredLength > 0); EmitSum(sliceStaticPos + requiredLength - 1, dynamicRequiredLength); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } // Emits code to get ref slice[sliceStaticPos] void EmitTextSpanOffset() { Ldloc(slice); Call(s_memoryMarshalGetReference); if (sliceStaticPos > 0) { Ldc(sliceStaticPos * sizeof(char)); Add(); } } // Adds the value of sliceStaticPos into the pos local, slices textspan by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos() { if (sliceStaticPos > 0) { // pos += sliceStaticPos; Ldloc(pos); Ldc(sliceStaticPos); Add(); Stloc(pos); // slice = slice.Slice(sliceStaticPos); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Stloc(slice); // sliceStaticPos = 0; sliceStaticPos = 0; } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); Label originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // Label to jump to when any branch completes successfully. Label matchLabel = DefineLabel(); // Save off pos. We'll need to reset this each time a branch fails. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. LocalBuilder? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { // startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new Label[childCount]; Label backtrackLabel = DefineLabel(); for (int i = 0; i < childCount; i++) { bool isLastBranch = i == childCount - 1; Label nextBranch = default; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = DefineLabel(); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { // if (stackpos + 3 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = i; // base.runstack[stackpos++] = startingCapturePos; // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldc(i)); if (startingCapturePos is not null) { EmitStackPush(() => Ldloc(startingCapturePos)); } EmitStackPush(() => Ldloc(startingPos)); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. // pos += sliceStaticPos; // sliceStaticPos = 0; // goto matchLabel; TransferSliceStaticPosToPos(); BrFar(matchLabel); // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { // NextBranch: // pos = startingPos; // slice = inputSpan.Slice(pos); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); MarkLabel(nextBranch); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel); // startingPos = base.runstack[--stackpos]; // startingCapturePos = base.runstack[--stackpos]; // switch (base.runstack[--stackpos]) { ... } // branch number EmitStackPop(); Stloc(startingPos); if (startingCapturePos is not null) { EmitStackPop(); Stloc(startingCapturePos); } EmitStackPop(); Switch(labelMap); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); TransferSliceStaticPosToPos(); Label backreferenceEnd = DefineLabel(); // if (!base.IsMatched(capnum)) goto (ecmascript ? end : doneLabel); Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar((node.Options & RegexOptions.ECMAScript) == 0 ? doneLabel : backreferenceEnd); using RentedLocalBuilder matchLength = RentInt32Local(); using RentedLocalBuilder matchIndex = RentInt32Local(); using RentedLocalBuilder i = RentInt32Local(); // int matchLength = base.MatchLength(capnum); Ldthis(); Ldc(capnum); Call(s_matchLengthMethod); Stloc(matchLength); // if (slice.Length < matchLength) goto doneLabel; Ldloca(slice); Call(s_spanGetLengthMethod); Ldloc(matchLength); BltFar(doneLabel); // int matchIndex = base.MatchIndex(capnum); Ldthis(); Ldc(capnum); Call(s_matchIndexMethod); Stloc(matchIndex); Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) Ldc(0); Stloc(i); Br(condition); MarkLabel(body); // if (inputSpan[matchIndex + i] != slice[i]) goto doneLabel; Ldloca(inputSpan); Ldloc(matchIndex); Ldloc(i); Add(); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } Ldloca(slice); Ldloc(i); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } BneFar(doneLabel); // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < matchLength; ...) MarkLabel(condition); Ldloc(i); Ldloc(matchLength); Blt(body); // pos += matchLength; Ldloc(pos); Ldloc(matchLength); Add(); Stloc(pos); SliceInputSpan(); MarkLabel(backreferenceEnd); } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label refNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder resumeAt = DeclareInt32(); // if (!base.IsMatched(capnum)) goto refNotMatched; Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar(refNotMatched); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { // goto endConditional; BrFar(endConditional); } MarkLabel(refNotMatched); Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt); } } if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // We're atomic by our parent, so even if either child branch has backtracking constructs, // we don't need to emit any backtracking logic in support, as nothing will backtrack in. // Instead, we just ensure we revert back to the original done label so that any backtracking // skips over this node. doneLabel = originalDoneLabel; if (needsEndConditional) { MarkLabel(endConditional); } } else { // Subsequent expressions might try to backtrack to here, so output a backtracking map based on resumeAt. // Skip the backtracking section // goto endConditional; Debug.Assert(needsEndConditional); Br(endConditional); // Backtrack section Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. // resumeAt = base.runstack[--stackpos]; EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postIfDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto originalDoneLabel; BrFar(originalDoneLabel); if (needsEndConditional) { MarkLabel(endConditional); } // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt)); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookahead. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label expressionNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder? resumeAt = null; if (!isAtomic) { resumeAt = DeclareInt32(); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. LocalBuilder? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { // int startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookahead; however, a positive lookahead only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookahead. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. EmitNode(condition); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt!); } // goto endConditional; BrFar(endConditional); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. // pos = startingPos; MarkLabel(expressionNotMatched); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt!); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt!); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // EndConditional: doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { Debug.Assert(resumeAt is not null); // Skip the backtracking section. BrFar(endConditional); Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // resumeAt = StackPop(); EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postYesDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto postConditionalDoneLabel; BrFar(originalDoneLabel); // EndConditional: MarkLabel(endConditional); // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt!)); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, _regexTree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); // startingPos = pos; TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); RegexNode child = node.Child(0); if (uncapnum != -1) { // if (!IsMatched(uncapnum)) goto doneLabel; Ldthis(); Ldc(uncapnum); Call(s_isMatchedMethod); BrfalseFar(doneLabel); } // Emit child node. Label originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); TransferSliceStaticPosToPos(); if (uncapnum == -1) { // Capture(capnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldloc(startingPos); Ldloc(pos); Call(s_captureMethod); } else { // TransferCapture(capnum, uncapnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldc(uncapnum); Ldloc(startingPos); Ldloc(pos); Call(s_transferCaptureMethod); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(startingPos)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); Br(backtrackingEnd); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); EmitStackPop(); Stloc(startingPos); if (!childBacktracks) { // pos = startingPos Ldloc(startingPos); Stloc(pos); SliceInputSpan(); } // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(LocalBuilder startingCapturePos) { Debug.Assert(startingCapturePos != null); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Ldloc(startingCapturePos); Bgt(body); } // Emits the code to handle a positive lookahead assertion. void EmitPositiveLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); // Save off pos. We'll need to reset this upon successful completion of the lookahead. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; } // Emits the code to handle a negative lookahead assertion. void EmitNegativeLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Label originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookahead. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; Label negativeLookaheadDoneLabel = DefineLabel(); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookahead, which actually // means failure for a _negative_ lookahead, so we need to jump to the original done. // goto originalDoneLabel; BrFar(originalDoneLabel); // Failures (success for a negative lookahead) jump here. MarkLabel(negativeLookaheadDoneLabel); if (doneLabel == negativeLookaheadDoneLabel) { doneLabel = originalDoneLabel; } // After the child completes in failure (success for negative lookahead), reset the text positions. // pos = startingPos; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Atomic: EmitAtomic(node, subsequent); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaheadAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaheadAssertion(node); break; case RegexNodeKind.Nothing: BrFar(doneLabel); break; case RegexNodeKind.Empty: // Emit nothing. break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); RegexNode child = node.Child(0); if (!analysis.MayBacktrack(child)) { // If the child has no backtracking, the atomic is a nop and we can just skip it. // Note that the source generator equivalent for this is in the top-level EmitNode, in order to avoid // outputting some extra comments and scopes. As such formatting isn't a concern for the compiler, // the logic is instead here in EmitAtomic. EmitNode(child, subsequent); return; } // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. Label originalDoneLabel = doneLabel; // int startingStackpos = stackpos; using RentedLocalBuilder startingStackpos = RentInt32Local(); Ldloc(stackpos); Stloc(startingStackpos); // Emit the child. EmitNode(child, subsequent); // Reset the stack position and done label. // stackpos = startingStackpos; Ldloc(startingStackpos); Stloc(stackpos); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); // if (base.runtextpos < pos) // { // base.runtextpos = pos; // } TransferSliceStaticPosToPos(); Ldthisfld(s_runtextposField); Ldloc(pos); Label skipUpdate = DefineLabel(); Bge(skipUpdate); Ldthis(); Ldloc(pos); Stfld(s_runtextposField); MarkLabel(skipUpdate); } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. if (emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { EmitSpanLengthCheck(requiredLength); for (; i < exclusiveEnd; i++) { EmitNode(node.Child(i), GetSubsequent(i, node, subsequent), emitLengthChecksIfRequired: false); } i--; continue; } EmitNode(node.Child(i), GetSubsequent(i, node, subsequent)); } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequent(int index, RegexNode node, RegexNode? subsequent) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return subsequent; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, LocalBuilder? offset = null) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); // This only emits a single check, but it's called from the looping constructs in a loop // to generate the code for a single check, so we check for each "family" (one, notone, set) // rather than only for the specific single character nodes. // if ((uint)(sliceStaticPos + offset) >= slice.Length || slice[sliceStaticPos + offset] != ch) goto Done; if (emitLengthCheck) { EmitSpanLengthCheck(1, offset); } Ldloca(slice); EmitSum(sliceStaticPos, offset); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(doneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(doneLabel); } else // IsNotoneFamily { BeqFar(doneLabel); } } sliceStaticPos++; } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); // if (!IsBoundary(inputSpan, pos + sliceStaticPos)) goto doneLabel; Ldthis(); Ldloc(inputSpan); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); } switch (node.Kind) { case RegexNodeKind.Boundary: Call(s_isBoundaryMethod); BrfalseFar(doneLabel); break; case RegexNodeKind.NonBoundary: Call(s_isBoundaryMethod); BrtrueFar(doneLabel); break; case RegexNodeKind.ECMABoundary: Call(s_isECMABoundaryMethod); BrfalseFar(doneLabel); break; default: Debug.Assert(node.Kind == RegexNodeKind.NonECMABoundary); Call(s_isECMABoundaryMethod); BrtrueFar(doneLabel); break; } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. BrFar(doneLabel); } else { // if (pos > 0/start) goto doneLabel; Ldloc(pos); if (node.Kind == RegexNodeKind.Beginning) { Ldc(0); } else { Ldthisfld(s_runtextstartField); } BneFar(doneLabel); } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { // if (slice[sliceStaticPos - 1] != '\n') goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos - 1); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the runtext field directly: // if (pos > 0 && base.runtext[pos - 1] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldc(0); Ble(success); Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; case RegexNodeKind.End: // if (sliceStaticPos < slice.Length) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BltUnFar(doneLabel); break; case RegexNodeKind.EndZ: // if (sliceStaticPos < slice.Length - 1) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); Ldc(1); Sub(); BltFar(doneLabel); goto case RegexNodeKind.Eol; case RegexNodeKind.Eol: // if (sliceStaticPos < slice.Length && slice[sliceStaticPos] != '\n') goto doneLabel; { Label success = DefineLabel(); Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); EmitMultiCharString(node.Str!, IsCaseInsensitive(node), emitLengthCheck); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck) { Debug.Assert(str.Length >= 2); if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } foreach (char c in str) { // if (c != slice[sliceStaticPos++]) goto doneLabel; EmitTextSpanOffset(); sliceStaticPos++; LdindU2(); CallToLower(); Ldc(c); BneFar(doneLabel); } } else { // if (!slice.Slice(sliceStaticPos).StartsWith("...") goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Ldstr(str); Call(s_stringAsSpanMethod); Call(s_spanStartsWith); BrfalseFar(doneLabel); sliceStaticPos += str.Length; } } // Emits the code to handle a backtracking, single-character loop. void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); Label backtrackingLabel = DefineLabel(); Label endLoop = DefineLabel(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder endingPos = DeclareInt32(); LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) // int startingPos = pos; Ldloc(pos); Stloc(startingPos); EmitSingleCharAtomicLoop(node); // pos += sliceStaticPos; // int endingPos = pos; TransferSliceStaticPosToPos(); Ldloc(pos); Stloc(endingPos); // int capturepos = base.Crawlpos(); if (capturepos is not null) { Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } // startingPos += node.M; if (node.M > 0) { Ldloc(startingPos); Ldc(node.M); Add(); Stloc(startingPos); } // goto endLoop; BrFar(endLoop); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel); if (capturepos is not null) { // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(capturepos); EmitUncaptureUntil(capturepos); } // endingPos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(endingPos); EmitStackPop(); Stloc(startingPos); // if (startingPos >= endingPos) goto doneLabel; Ldloc(startingPos); Ldloc(endingPos); BgeFar(doneLabel); if (subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { // endingPos = inputSpan.Slice(startingPos, Math.Min(inputSpan.Length, endingPos + literal.Length - 1) - startingPos).LastIndexOf(literal); // if (endingPos < 0) // { // goto doneLabel; // } Ldloca(inputSpan); Ldloc(startingPos); if (literal.Item2 is not null) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(endingPos); Ldc(literal.Item2.Length - 1); Add(); Call(s_mathMinIntInt); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); Ldstr(literal.Item2); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); } else { Ldloc(endingPos); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanLastIndexOfAnyCharChar); break; case 3: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Ldc(literal.Item3[2]); Call(s_spanLastIndexOfAnyCharCharChar); break; default: Ldstr(literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfAnySpan); break; } } else { Ldc(literal.Item1); Call(s_spanLastIndexOfChar); } } Stloc(endingPos); Ldloc(endingPos); Ldc(0); BltFar(doneLabel); // endingPos += startingPos; Ldloc(endingPos); Ldloc(startingPos); Add(); Stloc(endingPos); } else { // endingPos--; Ldloc(endingPos); Ldc(1); Sub(); Stloc(endingPos); } // pos = endingPos; Ldloc(endingPos); Stloc(pos); // slice = inputSpan.Slice(pos); SliceInputSpan(); MarkLabel(endLoop); EmitStackResizeIfNeeded(expressionHasCaptures ? 3 : 2); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(endingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos!)); } doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. LocalBuilder? iterationCount = null; int? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = node.N - node.M; // int iterationCount = 0; iterationCount = DeclareInt32(); Ldc(0); Stloc(iterationCount); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. // int startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. // goto endLoopLabel; Label endLoopLabel = DefineLabel(); BrFar(endLoopLabel); // Backtracking section. Subsequent failures will jump to here. Label backtrackingLabel = DefineLabel(); MarkLabel(backtrackingLabel); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturepos is not null) { // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitUncaptureUntil(capturepos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { // if (iterationCount >= maxIterations) goto doneLabel; Ldloc(iterationCount!); Ldc(maxIterations.Value); BgeFar(doneLabel); // iterationCount++; Ldloc(iterationCount!); Ldc(1); Add(); Stloc(iterationCount!); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. // pos = startingPos; // Match single char; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). // startingPos = slice.IndexOfAny(node.Ch, literal); Ldloc(slice); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(node.Ch); Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(node.Ch + literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(node.Ch); Ldc(literal.Item2?[0] ?? literal.Item1); Call(s_spanIndexOfAnyCharChar); } Stloc(startingPos); // if ((uint)startingPos >= (uint)slice.Length) goto doneLabel; Ldloc(startingPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); // if (slice[startingPos] == node.Ch) goto doneLabel; Ldloca(slice); Ldloc(startingPos); Call(s_spanGetItemMethod); LdindU2(); Ldc(node.Ch); BeqFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. // startingPos = slice.IndexOf(literal); Ldloc(slice); if (literal2.Item2 is not null) { Ldstr(literal2.Item2); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (literal2.Item3 is not null) { switch (literal2.Item3.Length) { case 2: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Ldc(literal2.Item3[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(literal2.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(literal2.Item1); Call(s_spanIndexOfChar); } Stloc(startingPos); // if (startingPos < 0) goto doneLabel; Ldloc(startingPos); Ldc(0); BltFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } // Store the position we've left off at in case we need to iterate again. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. Label originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes MarkLabel(endLoopLabel); if (capturepos is not null) { // capturepos = base.CrawlPos(); Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } if (node.IsInLoop()) { // Store the loop's state // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = capturepos; // base.runstack[stackpos++] = iterationCount; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos)); } if (iterationCount is not null) { EmitStackPush(() => Ldloc(iterationCount)); } // Skip past the backtracking section Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; if (iterationCount is not null) { EmitStackPop(); Stloc(iterationCount); } if (capturepos is not null) { EmitStackPop(); Stloc(capturepos); } EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; Label originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); LocalBuilder sawEmpty = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = pos; // sawEmpty = 0; // false Ldc(0); Stloc(iterationCount); Ldloc(pos); Stloc(startingPos); Ldc(0); Stloc(sawEmpty); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { // goto endLoop; BrFar(endLoop); } // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. // base.runstack[stackpos++] = base.Crawlpos(); // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = pos; // base.runstack[stackpos++] = sawEmpty; EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); EmitStackPush(() => Ldloc(sawEmpty)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { // if (iterationCount < minIterations) goto body; Ldloc(iterationCount); Ldc(minIterations); BltFar(body); } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. // if (pos == startingPos) sawEmpty = 1; // true Label skipSawEmptySet = DefineLabel(); Ldloc(pos); Ldloc(startingPos); Bne(skipSawEmptySet); Ldc(1); Stloc(sawEmpty); MarkLabel(skipSawEmptySet); // We matched the next iteration. Jump to the subsequent code. // goto endLoop; BrFar(endLoop); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // sawEmpty = base.runstack[--stackpos]; // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (doneLabel == originalDoneLabel) { // goto originalDoneLabel; BrFar(originalDoneLabel); } else { // if (iterationCount == 0) goto originalDoneLabel; // goto doneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); BrFar(doneLabel); } MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); EmitStackPush(() => Ldloc(sawEmpty)); Label skipBacktrack = DefineLabel(); BrFar(skipBacktrack); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // sawEmpty = base.runstack[--stackpos]; // iterationCount = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); if (maxIterations == int.MaxValue) { // if (sawEmpty != 0) goto doneLabel; Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } else { // if (iterationCount >= maxIterations || sawEmpty != 0) goto doneLabel; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(doneLabel); Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } // goto body; BrFar(body); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthChecksIfRequired); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthChecksIfRequired); return; } // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthChecksIfRequired) { EmitSpanLengthCheck(iterations); } // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; if (iterations <= MaxUnrollSize) { // if (slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // goto doneLabel; for (int i = 0; i < iterations; i++) { EmitSingleChar(node, emitLengthCheck: false); } } else { // ReadOnlySpan<char> tmp = slice.Slice(sliceStaticPos, iterations); // for (int i = 0; i < tmp.Length; i++) // { // TimeoutCheck(); // if (tmp[i] != ch) goto Done; // } // sliceStaticPos += iterations; Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); using RentedLocalBuilder spanLocal = RentReadOnlySpanCharLocal(); Ldloca(slice); Ldc(sliceStaticPos); Ldc(iterations); Call(s_spanSliceIntIntMethod); Stloc(spanLocal); using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); MarkLabel(bodyLabel); EmitTimeoutCheck(); LocalBuilder tmpTextSpanLocal = slice; // we want EmitSingleChar to refer to this temporary int tmpTextSpanPos = sliceStaticPos; slice = spanLocal; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: iterationLocal); slice = tmpTextSpanLocal; sliceStaticPos = tmpTextSpanPos; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldloca(spanLocal); Call(s_spanGetLengthMethod); BltFar(bodyLabel); sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; using RentedLocalBuilder iterationLocal = RentInt32Local(); Label atomicLoopDoneLabel = DefineLabel(); Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today int numSetChars = 0; if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. // int i = slice.Slice(sliceStaticPos).IndexOf(char); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } Ldc(node.Ch); Call(s_spanIndexOfChar); Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it would // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); // int i = slice.Slice(sliceStaticPos).IndexOfAny(ch1, ch2, ...); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } switch (numSetChars) { case 2: Ldc(setChars[0]); Ldc(setChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(setChars[0]); Ldc(setChars[1]); Ldc(setChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(setChars.Slice(0, numSetChars).ToString()); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); break; } Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. // int i = inputSpan.Length - pos; TransferSliceStaticPosToPos(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(pos); Sub(); Stloc(iterationLocal); } else { // For everything else, do a normal loop. // Transfer sliceStaticPos to pos to help with bounds check elimination on the loop. TransferSliceStaticPosToPos(); Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if ((uint)i >= (uint)slice.Length) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(atomicLoopDoneLabel); // if (slice[i] != ch) goto atomicLoopDoneLabel; Ldloca(slice); Ldloc(iterationLocal); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } // Done: MarkLabel(atomicLoopDoneLabel); // Check to ensure we've found at least min iterations. if (minIterations > 0) { Ldloc(iterationLocal); Ldc(minIterations); BltFar(doneLabel); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. // slice = slice.Slice(i); Ldloca(slice); Ldloc(iterationLocal); Call(s_spanSliceIntMethod); Stloc(slice); // pos += i; Ldloc(pos); Ldloc(iterationLocal); Add(); Stloc(pos); } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); Label skipUpdatesLabel = DefineLabel(); // if ((uint)sliceStaticPos >= (uint)slice.Length) goto skipUpdatesLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(skipUpdatesLabel); // if (slice[sliceStaticPos] != ch) goto skipUpdatesLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(skipUpdatesLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(skipUpdatesLabel); } else // IsNotoneFamily { BeqFar(skipUpdatesLabel); } } // slice = slice.Slice(1); Ldloca(slice); Ldc(1); Call(s_spanSliceIntMethod); Stloc(slice); // pos++; Ldloc(pos); Ldc(1); Add(); Stloc(pos); MarkLabel(skipUpdatesLabel); } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder i = RentInt32Local(); Ldc(0); Stloc(i); BrFar(condition); MarkLabel(body); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < node.M; ...) MarkLabel(condition); Ldloc(i); Ldc(node.M); BltFar(body); } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); Label originalDoneLabel = doneLabel; LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = 0; Ldc(0); Stloc(iterationCount); Ldc(0); Stloc(startingPos); // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { // base.runstack[stackpos++] = base.Crawlpos(); EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. Otherwise, // we've matched as many iterations as we can with this configuration. Jump to what comes after the loop. switch ((minIterations > 0, maxIterations == int.MaxValue)) { case (true, true): // if (pos != startingPos || iterationCount < minIterations) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (true, false): // if ((pos != startingPos || iterationCount < minIterations) && iterationCount < maxIterations) goto body; // goto endLoop; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (false, true): // if (pos != startingPos) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); BrFar(endLoop); break; case (false, false): // if (pos == startingPos || iterationCount >= maxIterations) goto endLoop; // goto body; Ldloc(pos); Ldloc(startingPos); BeqFar(endLoop); Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); BrFar(body); break; } // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { // int poppedCrawlPos = base.runstack[--stackpos]; // while (base.Crawlpos() > poppedCrawlPos) base.Uncapture(); using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (minIterations > 0) { // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // if (iterationCount < minIterations) goto doneLabel/originalDoneLabel; Ldloc(iterationCount); Ldc(minIterations); BltFar(childBacktracks ? doneLabel : originalDoneLabel); } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { // goto endLoop; BrFar(endLoop); // Backtrack: Label backtrack = DefineLabel(); MarkLabel(backtrack); // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { // Store the loop's state EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--runstack]; // startingPos = base.runstack[--runstack]; EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } } void EmitStackResizeIfNeeded(int count) { Debug.Assert(count >= 1); // if (stackpos >= base.runstack!.Length - (count - 1)) // { // Array.Resize(ref base.runstack, base.runstack.Length * 2); // } Label skipResize = DefineLabel(); Ldloc(stackpos); Ldthisfld(s_runstackField); Ldlen(); if (count > 1) { Ldc(count - 1); Sub(); } Blt(skipResize); Ldthis(); _ilg!.Emit(OpCodes.Ldflda, s_runstackField); Ldthisfld(s_runstackField); Ldlen(); Ldc(2); Mul(); Call(s_arrayResize); MarkLabel(skipResize); } void EmitStackPush(Action load) { // base.runstack[stackpos] = load(); Ldthisfld(s_runstackField); Ldloc(stackpos); load(); StelemI4(); // stackpos++; Ldloc(stackpos); Ldc(1); Add(); Stloc(stackpos); } void EmitStackPop() { // ... = base.runstack[--stackpos]; Ldthisfld(s_runstackField); Ldloc(stackpos); Ldc(1); Sub(); Stloc(stackpos); Ldloc(stackpos); LdelemI4(); } } protected void EmitScan(DynamicMethod tryFindNextStartingPositionMethod, DynamicMethod tryMatchAtCurrentPositionMethod) { Label returnLabel = DefineLabel(); // while (TryFindNextPossibleStartingPosition(text)) Label whileLoopBody = DefineLabel(); MarkLabel(whileLoopBody); Ldthis(); Ldarg_1(); Call(tryFindNextStartingPositionMethod); BrfalseFar(returnLabel); if (_hasTimeout) { // CheckTimeout(); Ldthis(); Call(s_checkTimeoutMethod); } // if (TryMatchAtCurrentPosition(text) || runtextpos == text.length) // return; Ldthis(); Ldarg_1(); Call(tryMatchAtCurrentPositionMethod); BrtrueFar(returnLabel); Ldthisfld(s_runtextposField); Ldarga_s(1); Call(s_spanGetLengthMethod); Ceq(); BrtrueFar(returnLabel); // runtextpos += 1 Ldthis(); Ldthisfld(s_runtextposField); Ldc(1); Add(); Stfld(s_runtextposField); // End loop body. BrFar(whileLoopBody); // return; MarkLabel(returnLabel); Ret(); } private void InitializeCultureForTryMatchAtCurrentPositionIfNecessary(AnalysisResults analysis) { _textInfo = null; if (analysis.HasIgnoreCase && (_options & RegexOptions.CultureInvariant) == 0) { // cache CultureInfo in local variable which saves excessive thread local storage accesses _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } /// <summary>Emits a a check for whether the character is in the specified character class.</summary> /// <remarks>The character to be checked has already been loaded onto the stack.</remarks> private void EmitMatchCharacterClass(string charClass, bool caseInsensitive) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // true Pop(); Ldc(1); return; case RegexCharClass.DigitClass: // char.IsDigit(ch) Call(s_charIsDigitMethod); return; case RegexCharClass.NotDigitClass: // !char.IsDigit(ch) Call(s_charIsDigitMethod); Ldc(0); Ceq(); return; case RegexCharClass.SpaceClass: // char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); return; case RegexCharClass.NotSpaceClass: // !char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); Ldc(0); Ceq(); return; case RegexCharClass.WordClass: // RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); return; case RegexCharClass.NotWordClass: // !RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); Ldc(0); Ceq(); return; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant; if (!invariant) { CallToLower(); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { if (lowInclusive == highInclusive) { // ch == charClass[3] Ldc(lowInclusive); Ceq(); } else { // (uint)ch - lowInclusive < highInclusive - lowInclusive + 1 Ldc(lowInclusive); Sub(); Ldc(highInclusive - lowInclusive + 1); CltUn(); } // Negate the answer if the negation flag was set if (RegexCharClass.IsNegated(charClass)) { Ldc(0); Ceq(); } return; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { // char.GetUnicodeCategory(ch) == category Call(s_charGetUnicodeInfo); Ldc((int)category); Ceq(); if (negated) { Ldc(0); Ceq(); } return; } // All checks after this point require reading the input character multiple times, // so we store it into a temporary local. using RentedLocalBuilder tempLocal = RentInt32Local(); Stloc(tempLocal); // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it's cheaper and smaller to compare against each than it is to use a lookup table. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int numChars = RegexCharClass.GetSetChars(charClass, setChars); if (numChars is 2 or 3) { if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out int mask)) // special-case common case of an upper and lowercase ASCII letter combination { // ((ch | mask) == setChars[1]) Ldloc(tempLocal); Ldc(mask); Or(); Ldc(setChars[1] | mask); Ceq(); } else { // (ch == setChars[0]) | (ch == setChars[1]) Ldloc(tempLocal); Ldc(setChars[0]); Ceq(); Ldloc(tempLocal); Ldc(setChars[1]); Ceq(); Or(); } // | (ch == setChars[2]) if (numChars == 3) { Ldloc(tempLocal); Ldc(setChars[2]); Ceq(); Or(); } return; } } using RentedLocalBuilder resultLocal = RentInt32Local(); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); // Helper method that emits a call to RegexRunner.CharInClass(ch{.ToLowerInvariant()}, charClass) void EmitCharInClass() { Ldloc(tempLocal); if (invariant) { CallToLower(); } Ldstr(charClass); Call(s_charInClassMethod); Stloc(resultLocal); } Label doneLabel = DefineLabel(); Label comparisonLabel = DefineLabel(); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) // ch >= 128 && RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(0); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. // ch < 128 || RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(1); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = string.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. // ch < 128 ? (bitVectorString[ch >> 4] & (1 << (ch & 0xF))) != 0 : Ldloc(tempLocal); Ldc(128); Bge(comparisonLabel); Ldstr(bitVectorString); Ldloc(tempLocal); Ldc(4); Shr(); Call(s_stringGetCharsMethod); Ldc(1); Ldloc(tempLocal); Ldc(15); And(); Ldc(31); And(); Shl(); And(); Ldc(0); CgtUn(); Stloc(resultLocal); Br(doneLabel); MarkLabel(comparisonLabel); if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. Ldc(0); Stloc(resultLocal); } else if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. Ldc(1); Stloc(resultLocal); } else { // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. EmitCharInClass(); } MarkLabel(doneLabel); Ldloc(resultLocal); } /// <summary>Emits a timeout check.</summary> private void EmitTimeoutCheck() { if (!_hasTimeout) { return; } Debug.Assert(_loopTimeoutCounter != null); // Increment counter for each loop iteration. Ldloc(_loopTimeoutCounter); Ldc(1); Add(); Stloc(_loopTimeoutCounter); // Emit code to check the timeout every 2048th iteration. Label label = DefineLabel(); Ldloc(_loopTimeoutCounter); Ldc(LoopTimeoutCheckCount); RemUn(); Brtrue(label); Ldthis(); Call(s_checkTimeoutMethod); MarkLabel(label); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions { /// <summary> /// RegexCompiler translates a block of RegexCode to MSIL, and creates a subclass of the RegexRunner type. /// </summary> internal abstract class RegexCompiler { private static readonly FieldInfo s_runtextstartField = RegexRunnerField("runtextstart"); private static readonly FieldInfo s_runtextposField = RegexRunnerField("runtextpos"); private static readonly FieldInfo s_runstackField = RegexRunnerField("runstack"); private static readonly MethodInfo s_captureMethod = RegexRunnerMethod("Capture"); private static readonly MethodInfo s_transferCaptureMethod = RegexRunnerMethod("TransferCapture"); private static readonly MethodInfo s_uncaptureMethod = RegexRunnerMethod("Uncapture"); private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched"); private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength"); private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex"); private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_isWordCharMethod = RegexRunnerMethod("IsWordChar"); private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos"); private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass"); private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout"); private static readonly MethodInfo s_charIsDigitMethod = typeof(char).GetMethod("IsDigit", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charIsWhiteSpaceMethod = typeof(char).GetMethod("IsWhiteSpace", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charGetUnicodeInfo = typeof(char).GetMethod("GetUnicodeCategory", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charToLowerInvariantMethod = typeof(char).GetMethod("ToLowerInvariant", new Type[] { typeof(char) })!; private static readonly MethodInfo s_cultureInfoGetCurrentCultureMethod = typeof(CultureInfo).GetMethod("get_CurrentCulture")!; private static readonly MethodInfo s_cultureInfoGetTextInfoMethod = typeof(CultureInfo).GetMethod("get_TextInfo")!; private static readonly MethodInfo s_spanGetItemMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Item", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanGetLengthMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Length")!; private static readonly MethodInfo s_memoryMarshalGetReference = typeof(MemoryMarshal).GetMethod("GetReference", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfChar = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfSpan = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!; private static readonly MethodInfo s_spanStartsWith = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_stringAsSpanMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string) })!; private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!; private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!; private static readonly MethodInfo s_arrayResize = typeof(Array).GetMethod("Resize")!.MakeGenericMethod(typeof(int)); private static readonly MethodInfo s_mathMinIntInt = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) })!; /// <summary>The ILGenerator currently in use.</summary> protected ILGenerator? _ilg; /// <summary>The options for the expression.</summary> protected RegexOptions _options; /// <summary>The <see cref="RegexTree"/> written for the expression.</summary> protected RegexTree? _regexTree; /// <summary>Whether this expression has a non-infinite timeout.</summary> protected bool _hasTimeout; /// <summary>Pool of Int32 LocalBuilders.</summary> private Stack<LocalBuilder>? _int32LocalsPool; /// <summary>Pool of ReadOnlySpan of char locals.</summary> private Stack<LocalBuilder>? _readOnlySpanCharLocalsPool; /// <summary>Local representing a cached TextInfo for the culture to use for all case-insensitive operations.</summary> private LocalBuilder? _textInfo; /// <summary>Local representing a timeout counter for loops (set loops and node loops).</summary> private LocalBuilder? _loopTimeoutCounter; /// <summary>A frequency with which the timeout should be validated.</summary> private const int LoopTimeoutCheckCount = 2048; private static FieldInfo RegexRunnerField(string fieldname) => typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; private static MethodInfo RegexRunnerMethod(string methname) => typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; /// <summary> /// Entry point to dynamically compile a regular expression. The expression is compiled to /// an in-memory assembly. /// </summary> internal static RegexRunnerFactory? Compile(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) => new RegexLWCGCompiler().FactoryInstanceFromCode(pattern, regexTree, options, hasTimeout); /// <summary>A macro for _ilg.DefineLabel</summary> private Label DefineLabel() => _ilg!.DefineLabel(); /// <summary>A macro for _ilg.MarkLabel</summary> private void MarkLabel(Label l) => _ilg!.MarkLabel(l); /// <summary>A macro for _ilg.Emit(Opcodes.Ldstr, str)</summary> protected void Ldstr(string str) => _ilg!.Emit(OpCodes.Ldstr, str); /// <summary>A macro for the various forms of Ldc.</summary> protected void Ldc(int i) => _ilg!.Emit(OpCodes.Ldc_I4, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ldc_I8).</summary> protected void LdcI8(long i) => _ilg!.Emit(OpCodes.Ldc_I8, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ret).</summary> protected void Ret() => _ilg!.Emit(OpCodes.Ret); /// <summary>A macro for _ilg.Emit(OpCodes.Dup).</summary> protected void Dup() => _ilg!.Emit(OpCodes.Dup); /// <summary>A macro for _ilg.Emit(OpCodes.Rem_Un).</summary> private void RemUn() => _ilg!.Emit(OpCodes.Rem_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Ceq).</summary> private void Ceq() => _ilg!.Emit(OpCodes.Ceq); /// <summary>A macro for _ilg.Emit(OpCodes.Cgt_Un).</summary> private void CgtUn() => _ilg!.Emit(OpCodes.Cgt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Clt_Un).</summary> private void CltUn() => _ilg!.Emit(OpCodes.Clt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Pop).</summary> private void Pop() => _ilg!.Emit(OpCodes.Pop); /// <summary>A macro for _ilg.Emit(OpCodes.Add).</summary> private void Add() => _ilg!.Emit(OpCodes.Add); /// <summary>A macro for _ilg.Emit(OpCodes.Sub).</summary> private void Sub() => _ilg!.Emit(OpCodes.Sub); /// <summary>A macro for _ilg.Emit(OpCodes.Mul).</summary> private void Mul() => _ilg!.Emit(OpCodes.Mul); /// <summary>A macro for _ilg.Emit(OpCodes.And).</summary> private void And() => _ilg!.Emit(OpCodes.And); /// <summary>A macro for _ilg.Emit(OpCodes.Or).</summary> private void Or() => _ilg!.Emit(OpCodes.Or); /// <summary>A macro for _ilg.Emit(OpCodes.Shl).</summary> private void Shl() => _ilg!.Emit(OpCodes.Shl); /// <summary>A macro for _ilg.Emit(OpCodes.Shr).</summary> private void Shr() => _ilg!.Emit(OpCodes.Shr); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloca).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloca(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloca, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_U2).</summary> private void LdindU2() => _ilg!.Emit(OpCodes.Ldind_U2); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I4).</summary> private void LdindI4() => _ilg!.Emit(OpCodes.Ldind_I4); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I8).</summary> private void LdindI8() => _ilg!.Emit(OpCodes.Ldind_I8); /// <summary>A macro for _ilg.Emit(OpCodes.Unaligned).</summary> private void Unaligned(byte alignment) => _ilg!.Emit(OpCodes.Unaligned, alignment); /// <summary>A macro for _ilg.Emit(OpCodes.Stloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Stloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Stloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldarg_0).</summary> protected void Ldthis() => _ilg!.Emit(OpCodes.Ldarg_0); /// <summary>A macro for _ilgEmit(OpCodes.Ldarg_1) </summary> private void Ldarg_1() => _ilg!.Emit(OpCodes.Ldarg_1); /// <summary>A macro for Ldthis(); Ldfld();</summary> protected void Ldthisfld(FieldInfo ft) { Ldthis(); _ilg!.Emit(OpCodes.Ldfld, ft); } /// <summary>Fetches the address of argument in passed in <paramref name="position"/></summary> /// <param name="position">The position of the argument which address needs to be fetched.</param> private void Ldarga_s(int position) => _ilg!.Emit(OpCodes.Ldarga_S, position); /// <summary>A macro for Ldthis(); Ldfld(); Stloc();</summary> private void Mvfldloc(FieldInfo ft, LocalBuilder lt) { Ldthisfld(ft); Stloc(lt); } /// <summary>A macro for _ilg.Emit(OpCodes.Stfld).</summary> protected void Stfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Stfld, ft); /// <summary>A macro for _ilg.Emit(OpCodes.Callvirt, mt).</summary> protected void Callvirt(MethodInfo mt) => _ilg!.Emit(OpCodes.Callvirt, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Call, mt).</summary> protected void Call(MethodInfo mt) => _ilg!.Emit(OpCodes.Call, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (long form).</summary> private void BrfalseFar(Label l) => _ilg!.Emit(OpCodes.Brfalse, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue) (long form).</summary> private void BrtrueFar(Label l) => _ilg!.Emit(OpCodes.Brtrue, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br) (long form).</summary> private void BrFar(Label l) => _ilg!.Emit(OpCodes.Br, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble) (long form).</summary> private void BleFar(Label l) => _ilg!.Emit(OpCodes.Ble, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt) (long form).</summary> private void BltFar(Label l) => _ilg!.Emit(OpCodes.Blt, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_Un) (long form).</summary> private void BltUnFar(Label l) => _ilg!.Emit(OpCodes.Blt_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge) (long form).</summary> private void BgeFar(Label l) => _ilg!.Emit(OpCodes.Bge, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un) (long form).</summary> private void BgeUnFar(Label l) => _ilg!.Emit(OpCodes.Bge_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne) (long form).</summary> private void BneFar(Label l) => _ilg!.Emit(OpCodes.Bne_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq) (long form).</summary> private void BeqFar(Label l) => _ilg!.Emit(OpCodes.Beq, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue_S) (short jump).</summary> private void Brtrue(Label l) => _ilg!.Emit(OpCodes.Brtrue_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br_S) (short jump).</summary> private void Br(Label l) => _ilg!.Emit(OpCodes.Br_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble_S) (short jump).</summary> private void Ble(Label l) => _ilg!.Emit(OpCodes.Ble_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_S) (short jump).</summary> private void Blt(Label l) => _ilg!.Emit(OpCodes.Blt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_S) (short jump).</summary> private void Bge(Label l) => _ilg!.Emit(OpCodes.Bge_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un_S) (short jump).</summary> private void BgeUn(Label l) => _ilg!.Emit(OpCodes.Bge_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump).</summary> private void Bgt(Label l) => _ilg!.Emit(OpCodes.Bgt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne_S) (short jump).</summary> private void Bne(Label l) => _ilg!.Emit(OpCodes.Bne_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq_S) (short jump).</summary> private void Beq(Label l) => _ilg!.Emit(OpCodes.Beq_S, l); /// <summary>A macro for the Ldlen instruction.</summary> private void Ldlen() => _ilg!.Emit(OpCodes.Ldlen); /// <summary>A macro for the Ldelem_I4 instruction.</summary> private void LdelemI4() => _ilg!.Emit(OpCodes.Ldelem_I4); /// <summary>A macro for the Stelem_I4 instruction.</summary> private void StelemI4() => _ilg!.Emit(OpCodes.Stelem_I4); private void Switch(Label[] table) => _ilg!.Emit(OpCodes.Switch, table); /// <summary>Declares a local bool.</summary> private LocalBuilder DeclareBool() => _ilg!.DeclareLocal(typeof(bool)); /// <summary>Declares a local int.</summary> private LocalBuilder DeclareInt32() => _ilg!.DeclareLocal(typeof(int)); /// <summary>Declares a local CultureInfo.</summary> private LocalBuilder? DeclareTextInfo() => _ilg!.DeclareLocal(typeof(TextInfo)); /// <summary>Declares a local string.</summary> private LocalBuilder DeclareString() => _ilg!.DeclareLocal(typeof(string)); private LocalBuilder DeclareReadOnlySpanChar() => _ilg!.DeclareLocal(typeof(ReadOnlySpan<char>)); /// <summary>Rents an Int32 local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentInt32Local() => new RentedLocalBuilder( _int32LocalsPool ??= new Stack<LocalBuilder>(), _int32LocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareInt32()); /// <summary>Rents a ReadOnlySpan(char) local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentReadOnlySpanCharLocal() => new RentedLocalBuilder( _readOnlySpanCharLocalsPool ??= new Stack<LocalBuilder>(1), // capacity == 1 as we currently don't expect overlapping instances _readOnlySpanCharLocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareReadOnlySpanChar()); /// <summary>Returned a rented local to the pool.</summary> private struct RentedLocalBuilder : IDisposable { private readonly Stack<LocalBuilder> _pool; private readonly LocalBuilder _local; internal RentedLocalBuilder(Stack<LocalBuilder> pool, LocalBuilder local) { _local = local; _pool = pool; } public static implicit operator LocalBuilder(RentedLocalBuilder local) => local._local; public void Dispose() { Debug.Assert(_pool != null); Debug.Assert(_local != null); Debug.Assert(!_pool.Contains(_local)); _pool.Push(_local); this = default; } } /// <summary>Sets the culture local to CultureInfo.CurrentCulture.</summary> private void InitLocalCultureInfo() { Debug.Assert(_textInfo != null); Call(s_cultureInfoGetCurrentCultureMethod); Callvirt(s_cultureInfoGetTextInfoMethod); Stloc(_textInfo); } /// <summary>Whether ToLower operations should be performed with the invariant culture as opposed to the one in <see cref="_textInfo"/>.</summary> private bool UseToLowerInvariant => _textInfo == null || (_options & RegexOptions.CultureInvariant) != 0; /// <summary>Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c).</summary> private void CallToLower() { if (UseToLowerInvariant) { Call(s_charToLowerInvariantMethod); } else { using RentedLocalBuilder currentCharLocal = RentInt32Local(); Stloc(currentCharLocal); Ldloc(_textInfo!); Ldloc(currentCharLocal); Callvirt(s_textInfoToLowerMethod); } } /// <summary>Generates the implementation for TryFindNextPossibleStartingPosition.</summary> protected void EmitTryFindNextPossibleStartingPosition() { Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder pos = DeclareInt32(); _textInfo = null; if ((_options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = _regexTree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when _regexTree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } // Load necessary locals // int pos = base.runtextpos; // ReadOnlySpan<char> inputSpan = dynamicMethodArg; // TODO: We can reference the arg directly rather than using another local. Mvfldloc(s_runtextposField, pos); Ldarg_1(); Stloc(inputSpan); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = _regexTree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); Label returnFalse = DefineLabel(); Label finishedLengthCheck = DefineLabel(); // if (pos > inputSpan.Length - _code.Tree.MinRequiredLength) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength > 0) { Ldc(minRequiredLength); Sub(); } Ble(finishedLengthCheck); MarkLabel(returnFalse); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); Ldc(0); Ret(); MarkLabel(finishedLengthCheck); // Emit any anchors. if (GenerateAnchors()) { return; } // Either anchors weren't specified, or they don't completely root all matches to a specific location. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {_regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: // return true; Ldc(1); Ret(); break; } // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool GenerateAnchors() { Label label; // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: label = DefineLabel(); Ldloc(pos); Ldc(0); Ble(label); Br(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: label = DefineLabel(); Ldloc(pos); Ldthisfld(s_runtextstartField); Ble(label); Br(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; } } // Now handle anchors that boost the position but don't determine immediate success or failure. switch (_regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: { // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any prefix or char class searches. label = DefineLabel(); // if (pos > 0... Ldloc(pos!); Ldc(0); Ble(label); // ... && inputSpan[pos - 1] != '\n') { ... } Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Beq(label); // int tmp = inputSpan.Slice(pos).IndexOf('\n'); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldc('\n'); Call(s_spanIndexOfChar); using (RentedLocalBuilder newlinePos = RentInt32Local()) { Stloc(newlinePos); // if (newlinePos < 0 || newlinePos + pos + 1 > inputSpan.Length) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(newlinePos); Ldc(0); Blt(returnFalse); Ldloc(newlinePos); Ldloc(pos); Add(); Ldc(1); Add(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bgt(returnFalse); // pos += newlinePos + 1; Ldloc(pos); Ldloc(newlinePos); Add(); Ldc(1); Add(); Stloc(pos); // We've updated the position. Make sure there's still enough room in the input for a possible match. // if (pos > inputSpan.Length - minRequiredLength) returnFalse; Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength != 0) { Ldc(minRequiredLength); Sub(); } Ldloc(pos); BltFar(returnFalse); } MarkLabel(label); } break; } switch (_regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End or RegexNodeKind.EndZ when _regexTree.FindOptimizations.MaxPossibleLength is int maxLength: // Jump to the end, minus the max allowed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Bge(label); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Stloc(pos); MarkLabel(label); break; } } return false; } void EmitIndexOf_LeftToRight(string prefix) { using RentedLocalBuilder i = RentInt32Local(); // int i = inputSpan.Slice(pos).IndexOf(prefix); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); Stloc(i); // if (i < 0) goto ReturnFalse; Ldloc(i); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(i); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = _regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); using RentedLocalBuilder iLocal = RentInt32Local(); using RentedLocalBuilder textSpanLocal = RentReadOnlySpanCharLocal(); // ReadOnlySpan<char> span = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(textSpanLocal); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; Label checkSpanLengthLabel = default; Label charNotInClassLabel = default; Label loopBody = default; if (needLoop) { checkSpanLengthLabel = DefineLabel(); charNotInClassLabel = DefineLabel(); loopBody = DefineLabel(); // for (int i = 0; Ldc(0); Stloc(iLocal); BrFar(checkSpanLengthLabel); MarkLabel(loopBody); } if (canUseIndexOf) { setIndex = 1; if (needLoop) { // slice.Slice(iLocal + primarySet.Distance); Ldloca(textSpanLocal); Ldloc(iLocal); if (primarySet.Distance != 0) { Ldc(primarySet.Distance); Add(); } Call(s_spanSliceIntMethod); } else if (primarySet.Distance != 0) { // slice.Slice(primarySet.Distance) Ldloca(textSpanLocal); Ldc(primarySet.Distance); Call(s_spanSliceIntMethod); } else { // slice Ldloc(textSpanLocal); } switch (primarySet.Chars!.Length) { case 1: // tmp = ...IndexOf(setChars[0]); Ldc(primarySet.Chars[0]); Call(s_spanIndexOfChar); break; case 2: // tmp = ...IndexOfAny(setChars[0], setChars[1]); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: // tmp = ...IndexOfAny(setChars[0], setChars[1], setChars[2]}); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Ldc(primarySet.Chars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(primarySet.Chars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } if (needLoop) { // i += tmp; // if (tmp < 0) goto returnFalse; using (RentedLocalBuilder tmp = RentInt32Local()) { Stloc(tmp); Ldloc(iLocal); Ldloc(tmp); Add(); Stloc(iLocal); Ldloc(tmp); Ldc(0); BltFar(returnFalse); } } else { // i = tmp; // if (i < 0) goto returnFalse; Stloc(iLocal); Ldloc(iLocal); Ldc(0); BltFar(returnFalse); } // if (i >= slice.Length - (minRequiredLength - 1)) goto returnFalse; if (sets.Count > 1) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); Ldc(minRequiredLength - 1); Sub(); Ldloc(iLocal); BleFar(returnFalse); } } // if (!CharInClass(slice[i], prefix[0], "...")) continue; // if (!CharInClass(slice[i + 1], prefix[1], "...")) continue; // if (!CharInClass(slice[i + 2], prefix[2], "...")) continue; // ... Debug.Assert(setIndex is 0 or 1); for ( ; setIndex < sets.Count; setIndex++) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Ldloc(iLocal); if (sets[setIndex].Distance != 0) { Ldc(sets[setIndex].Distance); Add(); } Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(sets[setIndex].Set, sets[setIndex].CaseInsensitive); BrfalseFar(charNotInClassLabel); } // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(iLocal); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); if (needLoop) { MarkLabel(charNotInClassLabel); // for (...; ...; i++) Ldloc(iLocal); Ldc(1); Add(); Stloc(iLocal); // for (...; i < span.Length - (minRequiredLength - 1); ...); MarkLabel(checkSpanLengthLabel); Ldloc(iLocal); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); if (setsToUse > 1 || primarySet.Distance != 0) { Ldc(minRequiredLength - 1); Sub(); } BltFar(loopBody); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = _regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); // while (true) Label loopBody = DefineLabel(); Label loopEnd = DefineLabel(); MarkLabel(loopBody); // ReadOnlySpan<char> slice = inputSpan.Slice(pos); using RentedLocalBuilder slice = RentReadOnlySpanCharLocal(); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); // Find the literal. If we can't find it, we're done searching. // int i = slice.IndexOf(literal); // if (i < 0) break; using RentedLocalBuilder i = RentInt32Local(); Ldloc(slice); if (target.Literal.String is string literalString) { Ldstr(literalString); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (target.Literal.Chars is not char[] literalChars) { Ldc(target.Literal.Char); Call(s_spanIndexOfChar); } else { switch (literalChars.Length) { case 2: Ldc(literalChars[0]); Ldc(literalChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literalChars[0]); Ldc(literalChars[1]); Ldc(literalChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(literalChars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } Stloc(i); Ldloc(i); Ldc(0); BltFar(loopEnd); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. // int prev = i; using RentedLocalBuilder prev = RentInt32Local(); Ldloc(i); Stloc(prev); // while ((uint)--prev < (uint)slice.Length) && MatchCharClass(slice[prev])); Label innerLoopBody = DefineLabel(); Label innerLoopEnd = DefineLabel(); MarkLabel(innerLoopBody); Ldloc(prev); Ldc(1); Sub(); Stloc(prev); Ldloc(prev); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(innerLoopEnd); Ldloca(slice); Ldloc(prev); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(target.LoopNode.Str!, caseInsensitive: false); BrtrueFar(innerLoopBody); MarkLabel(innerLoopEnd); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. // if ((i - prev - 1) < target.LoopNode.M) // { // pos += i + 1; // continue; // } Label metMinimum = DefineLabel(); Ldloc(i); Ldloc(prev); Sub(); Ldc(1); Sub(); Ldc(target.LoopNode.M); Bge(metMinimum); Ldloc(pos); Ldloc(i); Add(); Ldc(1); Add(); Stloc(pos); BrFar(loopBody); MarkLabel(metMinimum); } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. // base.runtextpos = pos + prev + 1; // return true; Ldthis(); Ldloc(pos); Ldloc(prev); Add(); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); // } MarkLabel(loopEnd); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } /// <summary>Generates the implementation for TryMatchAtCurrentPosition.</summary> protected void EmitTryMatchAtCurrentPosition() { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); // Get the root Capture node of the tree. RegexNode node = _regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); // Skip the Capture node. We handle the implicit root capture specially. node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. // base.Capture(0, base.runtextpos, base.runtextpos + node.Str.Length); // base.runtextpos = base.runtextpos + node.Str.Length; // return true; Ldthis(); Dup(); Ldc(0); Ldthisfld(s_runtextposField); Dup(); Ldc(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1); Add(); Call(s_captureMethod); Ldthisfld(s_runtextposField); Ldc(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); return; // The source generator special-cases RegexNode.Empty, for purposes of code learning rather than // performance. Since that's not applicable to RegexCompiler, that code isn't mirrored here. } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(_regexTree); // Initialize the main locals used throughout the implementation. LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder originalPos = DeclareInt32(); LocalBuilder pos = DeclareInt32(); LocalBuilder slice = DeclareReadOnlySpanChar(); Label doneLabel = DefineLabel(); Label originalDoneLabel = doneLabel; if (_hasTimeout) { _loopTimeoutCounter = DeclareInt32(); } // CultureInfo culture = CultureInfo.CurrentCulture; // only if the whole expression or any subportion is ignoring case, and we're not using invariant InitializeCultureForTryMatchAtCurrentPositionIfNecessary(analysis); // ReadOnlySpan<char> inputSpan = input; Ldarg_1(); Stloc(inputSpan); // int pos = base.runtextpos; // int originalpos = pos; Ldthisfld(s_runtextposField); Stloc(pos); Ldloc(pos); Stloc(originalPos); // int stackpos = 0; LocalBuilder stackpos = DeclareInt32(); Ldc(0); Stloc(stackpos); // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(); // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // pos += sliceStaticPos; // base.runtextpos = pos; // Capture(0, originalpos, pos); // return true; Ldthis(); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); Stloc(pos); Ldloc(pos); } Stfld(s_runtextposField); Ldthis(); Ldc(0); Ldloc(originalPos); Ldloc(pos); Call(s_captureMethod); Ldc(1); Ret(); // NOTE: The following is a difference from the source generator. The source generator emits: // UncaptureUntil(0); // return false; // at every location where the all-up match is known to fail. In contrast, the compiler currently // emits this uncapture/return code in one place and jumps to it upon match failure. The difference // stems primarily from the return-at-each-location pattern resulting in cleaner / easier to read // source code, which is not an issue for RegexCompiler emitting IL instead of C#. // If the graph contained captures, undo any remaining to handle failed matches. if (expressionHasCaptures) { // while (base.Crawlpos() != 0) base.Uncapture(); Label finalReturnLabel = DefineLabel(); Br(finalReturnLabel); MarkLabel(originalDoneLabel); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Brtrue(body); // Done: MarkLabel(finalReturnLabel); } else { // Done: MarkLabel(originalDoneLabel); } // return false; Ldc(0); Ret(); // Generated code successfully. return; static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan() { // slice = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); } // Emits the sum of a constant and a value from a local. void EmitSum(int constant, LocalBuilder? local) { if (local == null) { Ldc(constant); } else if (constant == 0) { Ldloc(local); } else { Ldloc(local); Ldc(constant); Add(); } } // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, LocalBuilder? dynamicRequiredLength = null) { // if ((uint)(sliceStaticPos + requiredLength + dynamicRequiredLength - 1) >= (uint)slice.Length) goto Done; Debug.Assert(requiredLength > 0); EmitSum(sliceStaticPos + requiredLength - 1, dynamicRequiredLength); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } // Emits code to get ref slice[sliceStaticPos] void EmitTextSpanOffset() { Ldloc(slice); Call(s_memoryMarshalGetReference); if (sliceStaticPos > 0) { Ldc(sliceStaticPos * sizeof(char)); Add(); } } // Adds the value of sliceStaticPos into the pos local, slices textspan by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos() { if (sliceStaticPos > 0) { // pos += sliceStaticPos; Ldloc(pos); Ldc(sliceStaticPos); Add(); Stloc(pos); // slice = slice.Slice(sliceStaticPos); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Stloc(slice); // sliceStaticPos = 0; sliceStaticPos = 0; } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); Label originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // Label to jump to when any branch completes successfully. Label matchLabel = DefineLabel(); // Save off pos. We'll need to reset this each time a branch fails. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. LocalBuilder? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { // startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new Label[childCount]; Label backtrackLabel = DefineLabel(); for (int i = 0; i < childCount; i++) { bool isLastBranch = i == childCount - 1; Label nextBranch = default; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = DefineLabel(); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { // if (stackpos + 3 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = i; // base.runstack[stackpos++] = startingCapturePos; // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldc(i)); if (startingCapturePos is not null) { EmitStackPush(() => Ldloc(startingCapturePos)); } EmitStackPush(() => Ldloc(startingPos)); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. // pos += sliceStaticPos; // sliceStaticPos = 0; // goto matchLabel; TransferSliceStaticPosToPos(); BrFar(matchLabel); // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { // NextBranch: // pos = startingPos; // slice = inputSpan.Slice(pos); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); MarkLabel(nextBranch); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel); // startingPos = base.runstack[--stackpos]; // startingCapturePos = base.runstack[--stackpos]; // switch (base.runstack[--stackpos]) { ... } // branch number EmitStackPop(); Stloc(startingPos); if (startingCapturePos is not null) { EmitStackPop(); Stloc(startingCapturePos); } EmitStackPop(); Switch(labelMap); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); TransferSliceStaticPosToPos(); Label backreferenceEnd = DefineLabel(); // if (!base.IsMatched(capnum)) goto (ecmascript ? end : doneLabel); Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar((node.Options & RegexOptions.ECMAScript) == 0 ? doneLabel : backreferenceEnd); using RentedLocalBuilder matchLength = RentInt32Local(); using RentedLocalBuilder matchIndex = RentInt32Local(); using RentedLocalBuilder i = RentInt32Local(); // int matchLength = base.MatchLength(capnum); Ldthis(); Ldc(capnum); Call(s_matchLengthMethod); Stloc(matchLength); // if (slice.Length < matchLength) goto doneLabel; Ldloca(slice); Call(s_spanGetLengthMethod); Ldloc(matchLength); BltFar(doneLabel); // int matchIndex = base.MatchIndex(capnum); Ldthis(); Ldc(capnum); Call(s_matchIndexMethod); Stloc(matchIndex); Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) Ldc(0); Stloc(i); Br(condition); MarkLabel(body); // if (inputSpan[matchIndex + i] != slice[i]) goto doneLabel; Ldloca(inputSpan); Ldloc(matchIndex); Ldloc(i); Add(); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } Ldloca(slice); Ldloc(i); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } BneFar(doneLabel); // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < matchLength; ...) MarkLabel(condition); Ldloc(i); Ldloc(matchLength); Blt(body); // pos += matchLength; Ldloc(pos); Ldloc(matchLength); Add(); Stloc(pos); SliceInputSpan(); MarkLabel(backreferenceEnd); } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label refNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder resumeAt = DeclareInt32(); // if (!base.IsMatched(capnum)) goto refNotMatched; Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar(refNotMatched); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { // goto endConditional; BrFar(endConditional); } MarkLabel(refNotMatched); Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt); } } if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // We're atomic by our parent, so even if either child branch has backtracking constructs, // we don't need to emit any backtracking logic in support, as nothing will backtrack in. // Instead, we just ensure we revert back to the original done label so that any backtracking // skips over this node. doneLabel = originalDoneLabel; if (needsEndConditional) { MarkLabel(endConditional); } } else { // Subsequent expressions might try to backtrack to here, so output a backtracking map based on resumeAt. // Skip the backtracking section // goto endConditional; Debug.Assert(needsEndConditional); Br(endConditional); // Backtrack section Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. // resumeAt = base.runstack[--stackpos]; EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postIfDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto originalDoneLabel; BrFar(originalDoneLabel); if (needsEndConditional) { MarkLabel(endConditional); } // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt)); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookahead. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label expressionNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder? resumeAt = null; if (!isAtomic) { resumeAt = DeclareInt32(); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. LocalBuilder? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { // int startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookahead; however, a positive lookahead only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookahead. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. EmitNode(condition); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt!); } // goto endConditional; BrFar(endConditional); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. // pos = startingPos; MarkLabel(expressionNotMatched); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt!); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt!); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // EndConditional: doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { Debug.Assert(resumeAt is not null); // Skip the backtracking section. BrFar(endConditional); Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // resumeAt = StackPop(); EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postYesDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto postConditionalDoneLabel; BrFar(originalDoneLabel); // EndConditional: MarkLabel(endConditional); // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt!)); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, _regexTree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); // startingPos = pos; TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); RegexNode child = node.Child(0); if (uncapnum != -1) { // if (!IsMatched(uncapnum)) goto doneLabel; Ldthis(); Ldc(uncapnum); Call(s_isMatchedMethod); BrfalseFar(doneLabel); } // Emit child node. Label originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); TransferSliceStaticPosToPos(); if (uncapnum == -1) { // Capture(capnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldloc(startingPos); Ldloc(pos); Call(s_captureMethod); } else { // TransferCapture(capnum, uncapnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldc(uncapnum); Ldloc(startingPos); Ldloc(pos); Call(s_transferCaptureMethod); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(startingPos)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); Br(backtrackingEnd); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); EmitStackPop(); Stloc(startingPos); if (!childBacktracks) { // pos = startingPos Ldloc(startingPos); Stloc(pos); SliceInputSpan(); } // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(LocalBuilder startingCapturePos) { Debug.Assert(startingCapturePos != null); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Ldloc(startingCapturePos); Bgt(body); } // Emits the code to handle a positive lookahead assertion. void EmitPositiveLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); // Save off pos. We'll need to reset this upon successful completion of the lookahead. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookahead. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; } // Emits the code to handle a negative lookahead assertion. void EmitNegativeLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Label originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookahead. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; Label negativeLookaheadDoneLabel = DefineLabel(); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookahead, which actually // means failure for a _negative_ lookahead, so we need to jump to the original done. // goto originalDoneLabel; BrFar(originalDoneLabel); // Failures (success for a negative lookahead) jump here. MarkLabel(negativeLookaheadDoneLabel); if (doneLabel == negativeLookaheadDoneLabel) { doneLabel = originalDoneLabel; } // After the child completes in failure (success for negative lookahead), reset the text positions. // pos = startingPos; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Atomic: EmitAtomic(node, subsequent); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaheadAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaheadAssertion(node); break; case RegexNodeKind.Nothing: BrFar(doneLabel); break; case RegexNodeKind.Empty: // Emit nothing. break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); RegexNode child = node.Child(0); if (!analysis.MayBacktrack(child)) { // If the child has no backtracking, the atomic is a nop and we can just skip it. // Note that the source generator equivalent for this is in the top-level EmitNode, in order to avoid // outputting some extra comments and scopes. As such formatting isn't a concern for the compiler, // the logic is instead here in EmitAtomic. EmitNode(child, subsequent); return; } // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. Label originalDoneLabel = doneLabel; // int startingStackpos = stackpos; using RentedLocalBuilder startingStackpos = RentInt32Local(); Ldloc(stackpos); Stloc(startingStackpos); // Emit the child. EmitNode(child, subsequent); // Reset the stack position and done label. // stackpos = startingStackpos; Ldloc(startingStackpos); Stloc(stackpos); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); // if (base.runtextpos < pos) // { // base.runtextpos = pos; // } TransferSliceStaticPosToPos(); Ldthisfld(s_runtextposField); Ldloc(pos); Label skipUpdate = DefineLabel(); Bge(skipUpdate); Ldthis(); Ldloc(pos); Stfld(s_runtextposField); MarkLabel(skipUpdate); } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. if (emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { EmitSpanLengthCheck(requiredLength); for (; i < exclusiveEnd; i++) { EmitNode(node.Child(i), GetSubsequent(i, node, subsequent), emitLengthChecksIfRequired: false); } i--; continue; } EmitNode(node.Child(i), GetSubsequent(i, node, subsequent)); } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequent(int index, RegexNode node, RegexNode? subsequent) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return subsequent; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, LocalBuilder? offset = null) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); // This only emits a single check, but it's called from the looping constructs in a loop // to generate the code for a single check, so we check for each "family" (one, notone, set) // rather than only for the specific single character nodes. // if ((uint)(sliceStaticPos + offset) >= slice.Length || slice[sliceStaticPos + offset] != ch) goto Done; if (emitLengthCheck) { EmitSpanLengthCheck(1, offset); } Ldloca(slice); EmitSum(sliceStaticPos, offset); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(doneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(doneLabel); } else // IsNotoneFamily { BeqFar(doneLabel); } } sliceStaticPos++; } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); // if (!IsBoundary(inputSpan, pos + sliceStaticPos)) goto doneLabel; Ldthis(); Ldloc(inputSpan); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); } switch (node.Kind) { case RegexNodeKind.Boundary: Call(s_isBoundaryMethod); BrfalseFar(doneLabel); break; case RegexNodeKind.NonBoundary: Call(s_isBoundaryMethod); BrtrueFar(doneLabel); break; case RegexNodeKind.ECMABoundary: Call(s_isECMABoundaryMethod); BrfalseFar(doneLabel); break; default: Debug.Assert(node.Kind == RegexNodeKind.NonECMABoundary); Call(s_isECMABoundaryMethod); BrtrueFar(doneLabel); break; } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. BrFar(doneLabel); } else { // if (pos > 0/start) goto doneLabel; Ldloc(pos); if (node.Kind == RegexNodeKind.Beginning) { Ldc(0); } else { Ldthisfld(s_runtextstartField); } BneFar(doneLabel); } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { // if (slice[sliceStaticPos - 1] != '\n') goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos - 1); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the runtext field directly: // if (pos > 0 && base.runtext[pos - 1] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldc(0); Ble(success); Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; case RegexNodeKind.End: // if (sliceStaticPos < slice.Length) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BltUnFar(doneLabel); break; case RegexNodeKind.EndZ: // if (sliceStaticPos < slice.Length - 1) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); Ldc(1); Sub(); BltFar(doneLabel); goto case RegexNodeKind.Eol; case RegexNodeKind.Eol: // if (sliceStaticPos < slice.Length && slice[sliceStaticPos] != '\n') goto doneLabel; { Label success = DefineLabel(); Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); EmitMultiCharString(node.Str!, IsCaseInsensitive(node), emitLengthCheck); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck) { Debug.Assert(str.Length >= 2); if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } foreach (char c in str) { // if (c != slice[sliceStaticPos++]) goto doneLabel; EmitTextSpanOffset(); sliceStaticPos++; LdindU2(); CallToLower(); Ldc(c); BneFar(doneLabel); } } else { // if (!slice.Slice(sliceStaticPos).StartsWith("...") goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Ldstr(str); Call(s_stringAsSpanMethod); Call(s_spanStartsWith); BrfalseFar(doneLabel); sliceStaticPos += str.Length; } } // Emits the code to handle a backtracking, single-character loop. void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); Label backtrackingLabel = DefineLabel(); Label endLoop = DefineLabel(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder endingPos = DeclareInt32(); LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) // int startingPos = pos; Ldloc(pos); Stloc(startingPos); EmitSingleCharAtomicLoop(node); // pos += sliceStaticPos; // int endingPos = pos; TransferSliceStaticPosToPos(); Ldloc(pos); Stloc(endingPos); // int capturepos = base.Crawlpos(); if (capturepos is not null) { Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } // startingPos += node.M; if (node.M > 0) { Ldloc(startingPos); Ldc(node.M); Add(); Stloc(startingPos); } // goto endLoop; BrFar(endLoop); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel); if (capturepos is not null) { // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(capturepos); EmitUncaptureUntil(capturepos); } // endingPos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(endingPos); EmitStackPop(); Stloc(startingPos); // if (startingPos >= endingPos) goto doneLabel; Ldloc(startingPos); Ldloc(endingPos); BgeFar(doneLabel); if (subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { // endingPos = inputSpan.Slice(startingPos, Math.Min(inputSpan.Length, endingPos + literal.Length - 1) - startingPos).LastIndexOf(literal); // if (endingPos < 0) // { // goto doneLabel; // } Ldloca(inputSpan); Ldloc(startingPos); if (literal.Item2 is not null) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(endingPos); Ldc(literal.Item2.Length - 1); Add(); Call(s_mathMinIntInt); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); Ldstr(literal.Item2); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); } else { Ldloc(endingPos); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanLastIndexOfAnyCharChar); break; case 3: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Ldc(literal.Item3[2]); Call(s_spanLastIndexOfAnyCharCharChar); break; default: Ldstr(literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfAnySpan); break; } } else { Ldc(literal.Item1); Call(s_spanLastIndexOfChar); } } Stloc(endingPos); Ldloc(endingPos); Ldc(0); BltFar(doneLabel); // endingPos += startingPos; Ldloc(endingPos); Ldloc(startingPos); Add(); Stloc(endingPos); } else { // endingPos--; Ldloc(endingPos); Ldc(1); Sub(); Stloc(endingPos); } // pos = endingPos; Ldloc(endingPos); Stloc(pos); // slice = inputSpan.Slice(pos); SliceInputSpan(); MarkLabel(endLoop); EmitStackResizeIfNeeded(expressionHasCaptures ? 3 : 2); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(endingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos!)); } doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. LocalBuilder? iterationCount = null; int? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = node.N - node.M; // int iterationCount = 0; iterationCount = DeclareInt32(); Ldc(0); Stloc(iterationCount); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. // int startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. // goto endLoopLabel; Label endLoopLabel = DefineLabel(); BrFar(endLoopLabel); // Backtracking section. Subsequent failures will jump to here. Label backtrackingLabel = DefineLabel(); MarkLabel(backtrackingLabel); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturepos is not null) { // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitUncaptureUntil(capturepos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { // if (iterationCount >= maxIterations) goto doneLabel; Ldloc(iterationCount!); Ldc(maxIterations.Value); BgeFar(doneLabel); // iterationCount++; Ldloc(iterationCount!); Ldc(1); Add(); Stloc(iterationCount!); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. // pos = startingPos; // Match single char; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). // startingPos = slice.IndexOfAny(node.Ch, literal); Ldloc(slice); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(node.Ch); Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(node.Ch + literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(node.Ch); Ldc(literal.Item2?[0] ?? literal.Item1); Call(s_spanIndexOfAnyCharChar); } Stloc(startingPos); // if ((uint)startingPos >= (uint)slice.Length) goto doneLabel; Ldloc(startingPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); // if (slice[startingPos] == node.Ch) goto doneLabel; Ldloca(slice); Ldloc(startingPos); Call(s_spanGetItemMethod); LdindU2(); Ldc(node.Ch); BeqFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. // startingPos = slice.IndexOf(literal); Ldloc(slice); if (literal2.Item2 is not null) { Ldstr(literal2.Item2); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (literal2.Item3 is not null) { switch (literal2.Item3.Length) { case 2: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Ldc(literal2.Item3[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(literal2.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(literal2.Item1); Call(s_spanIndexOfChar); } Stloc(startingPos); // if (startingPos < 0) goto doneLabel; Ldloc(startingPos); Ldc(0); BltFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } // Store the position we've left off at in case we need to iterate again. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. Label originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes MarkLabel(endLoopLabel); if (capturepos is not null) { // capturepos = base.CrawlPos(); Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } if (node.IsInLoop()) { // Store the loop's state // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = capturepos; // base.runstack[stackpos++] = iterationCount; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos)); } if (iterationCount is not null) { EmitStackPush(() => Ldloc(iterationCount)); } // Skip past the backtracking section Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; if (iterationCount is not null) { EmitStackPop(); Stloc(iterationCount); } if (capturepos is not null) { EmitStackPop(); Stloc(capturepos); } EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; Label originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); LocalBuilder sawEmpty = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = pos; // sawEmpty = 0; // false Ldc(0); Stloc(iterationCount); Ldloc(pos); Stloc(startingPos); Ldc(0); Stloc(sawEmpty); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { // goto endLoop; BrFar(endLoop); } // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. // base.runstack[stackpos++] = base.Crawlpos(); // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = pos; // base.runstack[stackpos++] = sawEmpty; EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); EmitStackPush(() => Ldloc(sawEmpty)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { // if (iterationCount < minIterations) goto body; Ldloc(iterationCount); Ldc(minIterations); BltFar(body); } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. // if (pos == startingPos) sawEmpty = 1; // true Label skipSawEmptySet = DefineLabel(); Ldloc(pos); Ldloc(startingPos); Bne(skipSawEmptySet); Ldc(1); Stloc(sawEmpty); MarkLabel(skipSawEmptySet); // We matched the next iteration. Jump to the subsequent code. // goto endLoop; BrFar(endLoop); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // sawEmpty = base.runstack[--stackpos]; // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (doneLabel == originalDoneLabel) { // goto originalDoneLabel; BrFar(originalDoneLabel); } else { // if (iterationCount == 0) goto originalDoneLabel; // goto doneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); BrFar(doneLabel); } MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); EmitStackPush(() => Ldloc(sawEmpty)); Label skipBacktrack = DefineLabel(); BrFar(skipBacktrack); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // sawEmpty = base.runstack[--stackpos]; // iterationCount = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); if (maxIterations == int.MaxValue) { // if (sawEmpty != 0) goto doneLabel; Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } else { // if (iterationCount >= maxIterations || sawEmpty != 0) goto doneLabel; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(doneLabel); Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } // goto body; BrFar(body); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthChecksIfRequired); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthChecksIfRequired); return; } // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthChecksIfRequired) { EmitSpanLengthCheck(iterations); } // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; if (iterations <= MaxUnrollSize) { // if (slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // goto doneLabel; for (int i = 0; i < iterations; i++) { EmitSingleChar(node, emitLengthCheck: false); } } else { // ReadOnlySpan<char> tmp = slice.Slice(sliceStaticPos, iterations); // for (int i = 0; i < tmp.Length; i++) // { // TimeoutCheck(); // if (tmp[i] != ch) goto Done; // } // sliceStaticPos += iterations; Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); using RentedLocalBuilder spanLocal = RentReadOnlySpanCharLocal(); Ldloca(slice); Ldc(sliceStaticPos); Ldc(iterations); Call(s_spanSliceIntIntMethod); Stloc(spanLocal); using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); MarkLabel(bodyLabel); EmitTimeoutCheck(); LocalBuilder tmpTextSpanLocal = slice; // we want EmitSingleChar to refer to this temporary int tmpTextSpanPos = sliceStaticPos; slice = spanLocal; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: iterationLocal); slice = tmpTextSpanLocal; sliceStaticPos = tmpTextSpanPos; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldloca(spanLocal); Call(s_spanGetLengthMethod); BltFar(bodyLabel); sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; using RentedLocalBuilder iterationLocal = RentInt32Local(); Label atomicLoopDoneLabel = DefineLabel(); Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today int numSetChars = 0; if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. // int i = slice.Slice(sliceStaticPos).IndexOf(char); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } Ldc(node.Ch); Call(s_spanIndexOfChar); Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it would // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); // int i = slice.Slice(sliceStaticPos).IndexOfAny(ch1, ch2, ...); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } switch (numSetChars) { case 2: Ldc(setChars[0]); Ldc(setChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(setChars[0]); Ldc(setChars[1]); Ldc(setChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(setChars.Slice(0, numSetChars).ToString()); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); break; } Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. // int i = inputSpan.Length - pos; TransferSliceStaticPosToPos(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(pos); Sub(); Stloc(iterationLocal); } else { // For everything else, do a normal loop. // Transfer sliceStaticPos to pos to help with bounds check elimination on the loop. TransferSliceStaticPosToPos(); Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if ((uint)i >= (uint)slice.Length) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(atomicLoopDoneLabel); // if (slice[i] != ch) goto atomicLoopDoneLabel; Ldloca(slice); Ldloc(iterationLocal); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } // Done: MarkLabel(atomicLoopDoneLabel); // Check to ensure we've found at least min iterations. if (minIterations > 0) { Ldloc(iterationLocal); Ldc(minIterations); BltFar(doneLabel); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. // slice = slice.Slice(i); Ldloca(slice); Ldloc(iterationLocal); Call(s_spanSliceIntMethod); Stloc(slice); // pos += i; Ldloc(pos); Ldloc(iterationLocal); Add(); Stloc(pos); } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); Label skipUpdatesLabel = DefineLabel(); // if ((uint)sliceStaticPos >= (uint)slice.Length) goto skipUpdatesLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(skipUpdatesLabel); // if (slice[sliceStaticPos] != ch) goto skipUpdatesLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(skipUpdatesLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(skipUpdatesLabel); } else // IsNotoneFamily { BeqFar(skipUpdatesLabel); } } // slice = slice.Slice(1); Ldloca(slice); Ldc(1); Call(s_spanSliceIntMethod); Stloc(slice); // pos++; Ldloc(pos); Ldc(1); Add(); Stloc(pos); MarkLabel(skipUpdatesLabel); } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder i = RentInt32Local(); Ldc(0); Stloc(i); BrFar(condition); MarkLabel(body); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < node.M; ...) MarkLabel(condition); Ldloc(i); Ldc(node.M); BltFar(body); } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); Label originalDoneLabel = doneLabel; LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = 0; Ldc(0); Stloc(iterationCount); Ldc(0); Stloc(startingPos); // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { // base.runstack[stackpos++] = base.Crawlpos(); EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. Otherwise, // we've matched as many iterations as we can with this configuration. Jump to what comes after the loop. switch ((minIterations > 0, maxIterations == int.MaxValue)) { case (true, true): // if (pos != startingPos || iterationCount < minIterations) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (true, false): // if ((pos != startingPos || iterationCount < minIterations) && iterationCount < maxIterations) goto body; // goto endLoop; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (false, true): // if (pos != startingPos) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); BrFar(endLoop); break; case (false, false): // if (pos == startingPos || iterationCount >= maxIterations) goto endLoop; // goto body; Ldloc(pos); Ldloc(startingPos); BeqFar(endLoop); Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); BrFar(body); break; } // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { // int poppedCrawlPos = base.runstack[--stackpos]; // while (base.Crawlpos() > poppedCrawlPos) base.Uncapture(); using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (minIterations > 0) { // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // if (iterationCount < minIterations) goto doneLabel/originalDoneLabel; Ldloc(iterationCount); Ldc(minIterations); BltFar(childBacktracks ? doneLabel : originalDoneLabel); } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { // goto endLoop; BrFar(endLoop); // Backtrack: Label backtrack = DefineLabel(); MarkLabel(backtrack); // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { // Store the loop's state EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--runstack]; // startingPos = base.runstack[--runstack]; EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } } void EmitStackResizeIfNeeded(int count) { Debug.Assert(count >= 1); // if (stackpos >= base.runstack!.Length - (count - 1)) // { // Array.Resize(ref base.runstack, base.runstack.Length * 2); // } Label skipResize = DefineLabel(); Ldloc(stackpos); Ldthisfld(s_runstackField); Ldlen(); if (count > 1) { Ldc(count - 1); Sub(); } Blt(skipResize); Ldthis(); _ilg!.Emit(OpCodes.Ldflda, s_runstackField); Ldthisfld(s_runstackField); Ldlen(); Ldc(2); Mul(); Call(s_arrayResize); MarkLabel(skipResize); } void EmitStackPush(Action load) { // base.runstack[stackpos] = load(); Ldthisfld(s_runstackField); Ldloc(stackpos); load(); StelemI4(); // stackpos++; Ldloc(stackpos); Ldc(1); Add(); Stloc(stackpos); } void EmitStackPop() { // ... = base.runstack[--stackpos]; Ldthisfld(s_runstackField); Ldloc(stackpos); Ldc(1); Sub(); Stloc(stackpos); Ldloc(stackpos); LdelemI4(); } } protected void EmitScan(DynamicMethod tryFindNextStartingPositionMethod, DynamicMethod tryMatchAtCurrentPositionMethod) { Label returnLabel = DefineLabel(); // while (TryFindNextPossibleStartingPosition(text)) Label whileLoopBody = DefineLabel(); MarkLabel(whileLoopBody); Ldthis(); Ldarg_1(); Call(tryFindNextStartingPositionMethod); BrfalseFar(returnLabel); if (_hasTimeout) { // CheckTimeout(); Ldthis(); Call(s_checkTimeoutMethod); } // if (TryMatchAtCurrentPosition(text) || runtextpos == text.length) // return; Ldthis(); Ldarg_1(); Call(tryMatchAtCurrentPositionMethod); BrtrueFar(returnLabel); Ldthisfld(s_runtextposField); Ldarga_s(1); Call(s_spanGetLengthMethod); Ceq(); BrtrueFar(returnLabel); // runtextpos += 1 Ldthis(); Ldthisfld(s_runtextposField); Ldc(1); Add(); Stfld(s_runtextposField); // End loop body. BrFar(whileLoopBody); // return; MarkLabel(returnLabel); Ret(); } private void InitializeCultureForTryMatchAtCurrentPositionIfNecessary(AnalysisResults analysis) { _textInfo = null; if (analysis.HasIgnoreCase && (_options & RegexOptions.CultureInvariant) == 0) { // cache CultureInfo in local variable which saves excessive thread local storage accesses _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } /// <summary>Emits a a check for whether the character is in the specified character class.</summary> /// <remarks>The character to be checked has already been loaded onto the stack.</remarks> private void EmitMatchCharacterClass(string charClass, bool caseInsensitive) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // true Pop(); Ldc(1); return; case RegexCharClass.DigitClass: // char.IsDigit(ch) Call(s_charIsDigitMethod); return; case RegexCharClass.NotDigitClass: // !char.IsDigit(ch) Call(s_charIsDigitMethod); Ldc(0); Ceq(); return; case RegexCharClass.SpaceClass: // char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); return; case RegexCharClass.NotSpaceClass: // !char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); Ldc(0); Ceq(); return; case RegexCharClass.WordClass: // RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); return; case RegexCharClass.NotWordClass: // !RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); Ldc(0); Ceq(); return; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant; if (!invariant) { CallToLower(); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { if (lowInclusive == highInclusive) { // ch == charClass[3] Ldc(lowInclusive); Ceq(); } else { // (uint)ch - lowInclusive < highInclusive - lowInclusive + 1 Ldc(lowInclusive); Sub(); Ldc(highInclusive - lowInclusive + 1); CltUn(); } // Negate the answer if the negation flag was set if (RegexCharClass.IsNegated(charClass)) { Ldc(0); Ceq(); } return; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { // char.GetUnicodeCategory(ch) == category Call(s_charGetUnicodeInfo); Ldc((int)category); Ceq(); if (negated) { Ldc(0); Ceq(); } return; } // All checks after this point require reading the input character multiple times, // so we store it into a temporary local. using RentedLocalBuilder tempLocal = RentInt32Local(); Stloc(tempLocal); // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it's cheaper and smaller to compare against each than it is to use a lookup table. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int numChars = RegexCharClass.GetSetChars(charClass, setChars); if (numChars is 2 or 3) { if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out int mask)) // special-case common case of an upper and lowercase ASCII letter combination { // ((ch | mask) == setChars[1]) Ldloc(tempLocal); Ldc(mask); Or(); Ldc(setChars[1] | mask); Ceq(); } else { // (ch == setChars[0]) | (ch == setChars[1]) Ldloc(tempLocal); Ldc(setChars[0]); Ceq(); Ldloc(tempLocal); Ldc(setChars[1]); Ceq(); Or(); } // | (ch == setChars[2]) if (numChars == 3) { Ldloc(tempLocal); Ldc(setChars[2]); Ceq(); Or(); } return; } } using RentedLocalBuilder resultLocal = RentInt32Local(); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); // Helper method that emits a call to RegexRunner.CharInClass(ch{.ToLowerInvariant()}, charClass) void EmitCharInClass() { Ldloc(tempLocal); if (invariant) { CallToLower(); } Ldstr(charClass); Call(s_charInClassMethod); Stloc(resultLocal); } Label doneLabel = DefineLabel(); Label comparisonLabel = DefineLabel(); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) // ch >= 128 && RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(0); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. // ch < 128 || RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(1); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = string.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. // ch < 128 ? (bitVectorString[ch >> 4] & (1 << (ch & 0xF))) != 0 : Ldloc(tempLocal); Ldc(128); Bge(comparisonLabel); Ldstr(bitVectorString); Ldloc(tempLocal); Ldc(4); Shr(); Call(s_stringGetCharsMethod); Ldc(1); Ldloc(tempLocal); Ldc(15); And(); Ldc(31); And(); Shl(); And(); Ldc(0); CgtUn(); Stloc(resultLocal); Br(doneLabel); MarkLabel(comparisonLabel); if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. Ldc(0); Stloc(resultLocal); } else if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. Ldc(1); Stloc(resultLocal); } else { // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. EmitCharInClass(); } MarkLabel(doneLabel); Ldloc(resultLocal); } /// <summary>Emits a timeout check.</summary> private void EmitTimeoutCheck() { if (!_hasTimeout) { return; } Debug.Assert(_loopTimeoutCounter != null); // Increment counter for each loop iteration. Ldloc(_loopTimeoutCounter); Ldc(1); Add(); Stloc(_loopTimeoutCounter); // Emit code to check the timeout every 2048th iteration. Label label = DefineLabel(); Ldloc(_loopTimeoutCounter); Ldc(LoopTimeoutCheckCount); RemUn(); Brtrue(label); Ldthis(); Call(s_checkTimeoutMethod); MarkLabel(label); } } }
1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexFindOptimizations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary>Contains state and provides operations related to finding the next location a match could possibly begin.</summary> internal sealed class RegexFindOptimizations { /// <summary>True if the input should be processed right-to-left rather than left-to-right.</summary> private readonly bool _rightToLeft; /// <summary>Provides the ToLower routine for lowercasing characters.</summary> private readonly TextInfo _textInfo; /// <summary>Lookup table used for optimizing ASCII when doing set queries.</summary> private readonly uint[]?[]? _asciiLookups; public RegexFindOptimizations(RegexNode root, RegexOptions options, CultureInfo culture) { _rightToLeft = (options & RegexOptions.RightToLeft) != 0; _textInfo = culture.TextInfo; MinRequiredLength = root.ComputeMinLength(); // Compute any anchor starting the expression. If there is one, we won't need to search for anything, // as we can just match at that single location. LeadingAnchor = RegexPrefixAnalyzer.FindLeadingAnchor(root); if (_rightToLeft && LeadingAnchor == RegexNodeKind.Bol) { // Filter out Bol for RightToLeft, as we don't currently optimize for it. LeadingAnchor = RegexNodeKind.Unknown; } if (LeadingAnchor is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.EndZ or RegexNodeKind.End) { FindMode = (LeadingAnchor, _rightToLeft) switch { (RegexNodeKind.Beginning, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning, (RegexNodeKind.Beginning, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning, (RegexNodeKind.Start, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start, (RegexNodeKind.Start, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start, (RegexNodeKind.End, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End, (RegexNodeKind.End, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End, (_, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ, (_, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ, }; return; } // Compute any anchor trailing the expression. If there is one, and we can also compute a fixed length // for the whole expression, we can use that to quickly jump to the right location in the input. if (!_rightToLeft) // haven't added FindNextStartingPositionMode support for RTL { bool triedToComputeMaxLength = false; TrailingAnchor = RegexPrefixAnalyzer.FindTrailingAnchor(root); if (TrailingAnchor is RegexNodeKind.End or RegexNodeKind.EndZ) { triedToComputeMaxLength = true; if (root.ComputeMaxLength() is int maxLength) { Debug.Assert(maxLength >= MinRequiredLength, $"{maxLength} should have been greater than {MinRequiredLength} minimum"); MaxPossibleLength = maxLength; if (MinRequiredLength == maxLength) { FindMode = TrailingAnchor == RegexNodeKind.End ? FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End : FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ; return; } } } if ((options & RegexOptions.NonBacktracking) != 0 && !triedToComputeMaxLength) { // NonBacktracking also benefits from knowing whether the pattern is a fixed length, as it can use that // knowledge to avoid multiple match phases in some situations. MaxPossibleLength = root.ComputeMaxLength(); } } // If there's a leading case-sensitive substring, just use IndexOf and inherit all of its optimizations. string caseSensitivePrefix = RegexPrefixAnalyzer.FindCaseSensitivePrefix(root); if (caseSensitivePrefix.Length > 1) { LeadingCaseSensitivePrefix = caseSensitivePrefix; FindMode = _rightToLeft ? FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive : FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive; return; } // At this point there are no fast-searchable anchors or case-sensitive prefixes. We can now analyze the // pattern for sets and then use any found sets to determine what kind of search to perform. // If we're compiling, then the compilation process already handles sets that reduce to a single literal, // so we can simplify and just always go for the sets. bool dfa = (options & RegexOptions.NonBacktracking) != 0; bool compiled = (options & RegexOptions.Compiled) != 0 && !dfa; // for now, we never generate code for NonBacktracking, so treat it as non-compiled bool interpreter = !compiled && !dfa; // For interpreter, we want to employ optimizations, but we don't want to make construction significantly // more expensive; someone who wants to pay to do more work can specify Compiled. So for the interpreter // we focus only on creating a set for the first character. Same for right-to-left, which is used very // rarely and thus we don't need to invest in special-casing it. if (_rightToLeft) { // Determine a set for anything that can possibly start the expression. if (RegexPrefixAnalyzer.FindFirstCharClass(root, culture) is (string CharClass, bool CaseInsensitive) set) { // See if the set is limited to holding only a few characters. Span<char> scratch = stackalloc char[5]; // max optimized by IndexOfAny today int scratchCount; char[]? chars = null; if (!RegexCharClass.IsNegated(set.CharClass) && (scratchCount = RegexCharClass.GetSetChars(set.CharClass, scratch)) > 0) { chars = scratch.Slice(0, scratchCount).ToArray(); } if (!compiled && chars is { Length: 1 }) { // The set contains one and only one character, meaning every match starts // with the same literal value (potentially case-insensitive). Search for that. FixedDistanceLiteral = (chars[0], 0); FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive; } else { // The set may match multiple characters. Search for that. FixedDistanceSets = new() { (chars, set.CharClass, 0, set.CaseInsensitive) }; FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive; _asciiLookups = new uint[1][]; } } return; } // We're now left-to-right only and looking for sets. // As a backup, see if we can find a literal after a leading atomic loop. That might be better than whatever sets we find, so // we want to know whether we have one in our pocket before deciding whether to use a leading set. (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? literalAfterLoop = RegexPrefixAnalyzer.FindLiteralFollowingLeadingLoop(root); // Build up a list of all of the sets that are a fixed distance from the start of the expression. List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? fixedDistanceSets = RegexPrefixAnalyzer.FindFixedDistanceSets(root, culture, thorough: !interpreter); Debug.Assert(fixedDistanceSets is null || fixedDistanceSets.Count != 0); // If we got such sets, we'll likely use them. However, if the best of them is something that doesn't support a vectorized // search and we did successfully find a literal after an atomic loop we could search instead, we prefer the vectorizable search. if (fixedDistanceSets is not null && (fixedDistanceSets[0].Chars is not null || literalAfterLoop is null)) { // Determine whether to do searching based on one or more sets or on a single literal. Compiled engines // don't need to special-case literals as they already do codegen to create the optimal lookup based on // the set's characteristics. if (!compiled && fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Chars is { Length: 1 }) { FixedDistanceLiteral = (fixedDistanceSets[0].Chars![0], fixedDistanceSets[0].Distance); FindMode = fixedDistanceSets[0].CaseInsensitive ? FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive : FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive; } else { // Limit how many sets we use to avoid doing lots of unnecessary work. The list was already // sorted from best to worst, so just keep the first ones up to our limit. const int MaxSetsToUse = 3; // arbitrary tuned limit if (fixedDistanceSets.Count > MaxSetsToUse) { fixedDistanceSets.RemoveRange(MaxSetsToUse, fixedDistanceSets.Count - MaxSetsToUse); } // Store the sets, and compute which mode to use. FixedDistanceSets = fixedDistanceSets; FindMode = (fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Distance == 0, fixedDistanceSets[0].CaseInsensitive) switch { (true, true) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive, (true, false) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive, (false, true) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive, (false, false) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive, }; _asciiLookups = new uint[fixedDistanceSets.Count][]; } return; } // If we found a literal we can search for after a leading set loop, use it. if (literalAfterLoop is not null) { FindMode = FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive; LiteralAfterLoop = literalAfterLoop; _asciiLookups = new uint[1][]; return; } } /// <summary>Gets the selected mode for performing the next <see cref="TryFindNextStartingPosition"/> operation</summary> public FindNextStartingPositionMode FindMode { get; } = FindNextStartingPositionMode.NoSearch; /// <summary>Gets the leading anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind LeadingAnchor { get; } /// <summary>Gets the trailing anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind TrailingAnchor { get; } /// <summary>Gets the minimum required length an input need be to match the pattern.</summary> /// <remarks>0 is a valid minimum length. This value may also be the max (and hence fixed) length of the expression.</remarks> public int MinRequiredLength { get; } /// <summary>The maximum possible length an input could be to match the pattern.</summary> /// <remarks> /// This is currently only set when <see cref="TrailingAnchor"/> is found to be an end anchor. /// That can be expanded in the future as needed. /// </remarks> public int? MaxPossibleLength { get; } /// <summary>Gets the leading prefix. May be an empty string.</summary> public string LeadingCaseSensitivePrefix { get; } = string.Empty; /// <summary>When in fixed distance literal mode, gets the literal and how far it is from the start of the pattern.</summary> public (char Literal, int Distance) FixedDistanceLiteral { get; } /// <summary>When in fixed distance set mode, gets the set and how far it is from the start of the pattern.</summary> /// <remarks>The case-insensitivity of the 0th entry will always match the mode selected, but subsequent entries may not.</remarks> public List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? FixedDistanceSets { get; } /// <summary>When in literal after set loop node, gets the literal to search for and the RegexNode representing the leading loop.</summary> public (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? LiteralAfterLoop { get; } /// <summary>Try to advance to the next starting position that might be a location for a match.</summary> /// <param name="textSpan">The text to search.</param> /// <param name="pos">The position in <paramref name="textSpan"/>. This is updated with the found position.</param> /// <param name="start">The index in <paramref name="textSpan"/> to consider the start for start anchor purposes.</param> /// <returns>true if a position to attempt a match was found; false if none was found.</returns> public bool TryFindNextStartingPosition(ReadOnlySpan<char> textSpan, ref int pos, int start) { // Return early if we know there's not enough input left to match. if (!_rightToLeft) { if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } else { if (pos < MinRequiredLength) { pos = 0; return false; } } // Optimize the handling of a Beginning-Of-Line (BOL) anchor (only for left-to-right). BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. if (LeadingAnchor == RegexNodeKind.Bol) { // If we're not currently positioned at the beginning of a line (either // the beginning of the string or just after a line feed), find the next // newline and position just after it. Debug.Assert(!_rightToLeft); int posm1 = pos - 1; if ((uint)posm1 < (uint)textSpan.Length && textSpan[posm1] != '\n') { int newline = textSpan.Slice(pos).IndexOf('\n'); if ((uint)newline > textSpan.Length - 1 - pos) { pos = textSpan.Length; return false; } pos = newline + 1 + pos; } } switch (FindMode) { // There's an anchor. For some, we can simply compare against the current position. // For others, we can jump to the relevant location. case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: if (pos > 0) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: if (pos > start) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: if (pos < textSpan.Length - 1) { pos = textSpan.Length - 1; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: if (pos < textSpan.Length) { pos = textSpan.Length; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: if (pos > 0) { pos = 0; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: if (pos < start) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: if (pos < textSpan.Length - 1 || ((uint)pos < (uint)textSpan.Length && textSpan[pos] != '\n')) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: if (pos < textSpan.Length) { pos = 0; return false; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: if (pos < textSpan.Length - MinRequiredLength - 1) { pos = textSpan.Length - MinRequiredLength - 1; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: if (pos < textSpan.Length - MinRequiredLength) { pos = textSpan.Length - MinRequiredLength; } return true; // There's a case-sensitive prefix. Search for it with ordinal IndexOf. case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: { int i = textSpan.Slice(pos).IndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos = i + LeadingCaseSensitivePrefix.Length; return true; } pos = 0; return false; } // There's a literal at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos = i + 1; return true; } pos = 0; return false; } case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive: { char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (ti.ToLower(span[i]) == ch) { pos = i + 1; return true; } } pos = 0; return false; } // There's a set at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: { (char[]? chars, string set, _, _) = FixedDistanceSets![0]; ReadOnlySpan<char> span = textSpan.Slice(pos); if (chars is not null) { int i = span.IndexOfAny(chars); if (i >= 0) { pos += i; return true; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos += i; return true; } } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos); for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos += i; return true; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } // There's a literal at a fixed offset from the beginning of the pattern. Search for it. case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); int i = textSpan.Slice(pos + FixedDistanceLiteral.Distance).IndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos + FixedDistanceLiteral.Distance); for (int i = 0; i < span.Length; i++) { if (ti.ToLower(span[i]) == ch) { pos += i; return true; } } pos = textSpan.Length; return false; } // There are one or more sets at fixed offsets from the start of the pattern. case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (char[]? primaryChars, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); if (primaryChars is not null) { for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { int offset = inputPosition + primaryDistance; int index = textSpan.Slice(offset).IndexOfAny(primaryChars); if (index < 0) { break; } index += offset; // The index here will be offset indexed due to the use of span, so we add offset to get // real position on the string. inputPosition = index - primaryDistance; if (inputPosition > endMinusRequiredLength) { break; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; char c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(c, primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (_, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); TextInfo ti = _textInfo; ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(ti.ToLower(c), primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } pos = textSpan.Length; return false; } // There's a literal after a leading set loop. Find the literal, then walk backwards through the loop to find the starting position. case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: { Debug.Assert(LiteralAfterLoop is not null); (RegexNode loopNode, (char Char, string? String, char[]? Chars) literal) = LiteralAfterLoop.GetValueOrDefault(); Debug.Assert(loopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(loopNode.N == int.MaxValue); int startingPos = pos; while (true) { ReadOnlySpan<char> slice = textSpan.Slice(startingPos); // Find the literal. If we can't find it, we're done searching. int i = literal.String is not null ? slice.IndexOf(literal.String.AsSpan()) : literal.Chars is not null ? slice.IndexOfAny(literal.Chars.AsSpan()) : slice.IndexOf(literal.Char); if (i < 0) { break; } // We found the literal. Walk backwards from it finding as many matches as we can against the loop. int prev = i; while ((uint)--prev < (uint)slice.Length && RegexCharClass.CharInClass(slice[prev], loopNode.Str!, ref _asciiLookups![0])) ; // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. if ((i - prev - 1) < loopNode.M) { startingPos += i + 1; continue; } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate literalPos as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. This might only be feasible for RegexCompiler // and the source generator after we refactor them to generate a single Scan method rather than separate // FindFirstChar / Go methods. pos = startingPos + prev + 1; return true; } pos = textSpan.Length; return false; } // Nothing special to look for. Just return true indicating this is a valid position to try to match. default: Debug.Assert(FindMode == FindNextStartingPositionMode.NoSearch); return true; } } } /// <summary>Mode to use for searching for the next location of a possible match.</summary> internal enum FindNextStartingPositionMode { /// <summary>A "beginning" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Beginning, /// <summary>A "start" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Start, /// <summary>An "endz" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_EndZ, /// <summary>An "end" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_End, /// <summary>A "beginning" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Beginning, /// <summary>A "start" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Start, /// <summary>An "endz" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_EndZ, /// <summary>An "end" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_End, /// <summary>An "end" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_End, /// <summary>An "endz" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_EndZ, /// <summary>A case-sensitive multi-character substring at the beginning of the pattern.</summary> LeadingPrefix_LeftToRight_CaseSensitive, /// <summary>A case-sensitive multi-character substring at the beginning of the right-to-left pattern.</summary> LeadingPrefix_RightToLeft_CaseSensitive, /// <summary>A case-sensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseSensitive, /// <summary>A case-insensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseInsensitive, /// <summary>A case-sensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseSensitive, /// <summary>A case-insensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseInsensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-sensitive.</summary> FixedSets_LeftToRight_CaseSensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-insensitive.</summary> FixedSets_LeftToRight_CaseInsensitive, /// <summary>A literal after a non-overlapping set loop at the start of the pattern. The literal is case-sensitive.</summary> LiteralAfterLoop_LeftToRight_CaseSensitive, /// <summary>Nothing to search for. Nop.</summary> NoSearch, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary>Contains state and provides operations related to finding the next location a match could possibly begin.</summary> internal sealed class RegexFindOptimizations { /// <summary>True if the input should be processed right-to-left rather than left-to-right.</summary> private readonly bool _rightToLeft; /// <summary>Provides the ToLower routine for lowercasing characters.</summary> private readonly TextInfo _textInfo; /// <summary>Lookup table used for optimizing ASCII when doing set queries.</summary> private readonly uint[]?[]? _asciiLookups; public RegexFindOptimizations(RegexNode root, RegexOptions options, CultureInfo culture) { _rightToLeft = (options & RegexOptions.RightToLeft) != 0; _textInfo = culture.TextInfo; MinRequiredLength = root.ComputeMinLength(); // Compute any anchor starting the expression. If there is one, we won't need to search for anything, // as we can just match at that single location. LeadingAnchor = RegexPrefixAnalyzer.FindLeadingAnchor(root); if (_rightToLeft && LeadingAnchor == RegexNodeKind.Bol) { // Filter out Bol for RightToLeft, as we don't currently optimize for it. LeadingAnchor = RegexNodeKind.Unknown; } if (LeadingAnchor is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.EndZ or RegexNodeKind.End) { FindMode = (LeadingAnchor, _rightToLeft) switch { (RegexNodeKind.Beginning, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning, (RegexNodeKind.Beginning, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning, (RegexNodeKind.Start, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start, (RegexNodeKind.Start, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start, (RegexNodeKind.End, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End, (RegexNodeKind.End, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End, (_, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ, (_, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ, }; return; } // Compute any anchor trailing the expression. If there is one, and we can also compute a fixed length // for the whole expression, we can use that to quickly jump to the right location in the input. if (!_rightToLeft) // haven't added FindNextStartingPositionMode support for RTL { bool triedToComputeMaxLength = false; TrailingAnchor = RegexPrefixAnalyzer.FindTrailingAnchor(root); if (TrailingAnchor is RegexNodeKind.End or RegexNodeKind.EndZ) { triedToComputeMaxLength = true; if (root.ComputeMaxLength() is int maxLength) { Debug.Assert(maxLength >= MinRequiredLength, $"{maxLength} should have been greater than {MinRequiredLength} minimum"); MaxPossibleLength = maxLength; if (MinRequiredLength == maxLength) { FindMode = TrailingAnchor == RegexNodeKind.End ? FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End : FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ; return; } } } if ((options & RegexOptions.NonBacktracking) != 0 && !triedToComputeMaxLength) { // NonBacktracking also benefits from knowing whether the pattern is a fixed length, as it can use that // knowledge to avoid multiple match phases in some situations. MaxPossibleLength = root.ComputeMaxLength(); } } // If there's a leading case-sensitive substring, just use IndexOf and inherit all of its optimizations. string caseSensitivePrefix = RegexPrefixAnalyzer.FindCaseSensitivePrefix(root); if (caseSensitivePrefix.Length > 1) { LeadingCaseSensitivePrefix = caseSensitivePrefix; FindMode = _rightToLeft ? FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive : FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive; return; } // At this point there are no fast-searchable anchors or case-sensitive prefixes. We can now analyze the // pattern for sets and then use any found sets to determine what kind of search to perform. // If we're compiling, then the compilation process already handles sets that reduce to a single literal, // so we can simplify and just always go for the sets. bool dfa = (options & RegexOptions.NonBacktracking) != 0; bool compiled = (options & RegexOptions.Compiled) != 0 && !dfa; // for now, we never generate code for NonBacktracking, so treat it as non-compiled bool interpreter = !compiled && !dfa; // For interpreter, we want to employ optimizations, but we don't want to make construction significantly // more expensive; someone who wants to pay to do more work can specify Compiled. So for the interpreter // we focus only on creating a set for the first character. Same for right-to-left, which is used very // rarely and thus we don't need to invest in special-casing it. if (_rightToLeft) { // Determine a set for anything that can possibly start the expression. if (RegexPrefixAnalyzer.FindFirstCharClass(root, culture) is (string CharClass, bool CaseInsensitive) set) { // See if the set is limited to holding only a few characters. Span<char> scratch = stackalloc char[5]; // max optimized by IndexOfAny today int scratchCount; char[]? chars = null; if (!RegexCharClass.IsNegated(set.CharClass) && (scratchCount = RegexCharClass.GetSetChars(set.CharClass, scratch)) > 0) { chars = scratch.Slice(0, scratchCount).ToArray(); } if (!compiled && chars is { Length: 1 }) { // The set contains one and only one character, meaning every match starts // with the same literal value (potentially case-insensitive). Search for that. FixedDistanceLiteral = (chars[0], 0); FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive; } else { // The set may match multiple characters. Search for that. FixedDistanceSets = new() { (chars, set.CharClass, 0, set.CaseInsensitive) }; FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive; _asciiLookups = new uint[1][]; } } return; } // We're now left-to-right only and looking for sets. // As a backup, see if we can find a literal after a leading atomic loop. That might be better than whatever sets we find, so // we want to know whether we have one in our pocket before deciding whether to use a leading set. (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? literalAfterLoop = RegexPrefixAnalyzer.FindLiteralFollowingLeadingLoop(root); // Build up a list of all of the sets that are a fixed distance from the start of the expression. List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? fixedDistanceSets = RegexPrefixAnalyzer.FindFixedDistanceSets(root, culture, thorough: !interpreter); Debug.Assert(fixedDistanceSets is null || fixedDistanceSets.Count != 0); // If we got such sets, we'll likely use them. However, if the best of them is something that doesn't support a vectorized // search and we did successfully find a literal after an atomic loop we could search instead, we prefer the vectorizable search. if (fixedDistanceSets is not null && (fixedDistanceSets[0].Chars is not null || literalAfterLoop is null)) { // Determine whether to do searching based on one or more sets or on a single literal. Compiled engines // don't need to special-case literals as they already do codegen to create the optimal lookup based on // the set's characteristics. if (!compiled && fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Chars is { Length: 1 }) { FixedDistanceLiteral = (fixedDistanceSets[0].Chars![0], fixedDistanceSets[0].Distance); FindMode = fixedDistanceSets[0].CaseInsensitive ? FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive : FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive; } else { // Limit how many sets we use to avoid doing lots of unnecessary work. The list was already // sorted from best to worst, so just keep the first ones up to our limit. const int MaxSetsToUse = 3; // arbitrary tuned limit if (fixedDistanceSets.Count > MaxSetsToUse) { fixedDistanceSets.RemoveRange(MaxSetsToUse, fixedDistanceSets.Count - MaxSetsToUse); } // Store the sets, and compute which mode to use. FixedDistanceSets = fixedDistanceSets; FindMode = (fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Distance == 0, fixedDistanceSets[0].CaseInsensitive) switch { (true, true) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive, (true, false) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive, (false, true) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive, (false, false) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive, }; _asciiLookups = new uint[fixedDistanceSets.Count][]; } return; } // If we found a literal we can search for after a leading set loop, use it. if (literalAfterLoop is not null) { FindMode = FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive; LiteralAfterLoop = literalAfterLoop; _asciiLookups = new uint[1][]; return; } } /// <summary>Gets the selected mode for performing the next <see cref="TryFindNextStartingPosition"/> operation</summary> public FindNextStartingPositionMode FindMode { get; } = FindNextStartingPositionMode.NoSearch; /// <summary>Gets the leading anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind LeadingAnchor { get; } /// <summary>Gets the trailing anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind TrailingAnchor { get; } /// <summary>Gets the minimum required length an input need be to match the pattern.</summary> /// <remarks>0 is a valid minimum length. This value may also be the max (and hence fixed) length of the expression.</remarks> public int MinRequiredLength { get; } /// <summary>The maximum possible length an input could be to match the pattern.</summary> /// <remarks> /// This is currently only set when <see cref="TrailingAnchor"/> is found to be an end anchor. /// That can be expanded in the future as needed. /// </remarks> public int? MaxPossibleLength { get; } /// <summary>Gets the leading prefix. May be an empty string.</summary> public string LeadingCaseSensitivePrefix { get; } = string.Empty; /// <summary>When in fixed distance literal mode, gets the literal and how far it is from the start of the pattern.</summary> public (char Literal, int Distance) FixedDistanceLiteral { get; } /// <summary>When in fixed distance set mode, gets the set and how far it is from the start of the pattern.</summary> /// <remarks>The case-insensitivity of the 0th entry will always match the mode selected, but subsequent entries may not.</remarks> public List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? FixedDistanceSets { get; } /// <summary>When in literal after set loop node, gets the literal to search for and the RegexNode representing the leading loop.</summary> public (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? LiteralAfterLoop { get; } /// <summary>Try to advance to the next starting position that might be a location for a match.</summary> /// <param name="textSpan">The text to search.</param> /// <param name="pos">The position in <paramref name="textSpan"/>. This is updated with the found position.</param> /// <param name="start">The index in <paramref name="textSpan"/> to consider the start for start anchor purposes.</param> /// <returns>true if a position to attempt a match was found; false if none was found.</returns> public bool TryFindNextStartingPosition(ReadOnlySpan<char> textSpan, ref int pos, int start) { // Return early if we know there's not enough input left to match. if (!_rightToLeft) { if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } else { if (pos < MinRequiredLength) { pos = 0; return false; } } // Optimize the handling of a Beginning-Of-Line (BOL) anchor (only for left-to-right). BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. if (LeadingAnchor == RegexNodeKind.Bol) { // If we're not currently positioned at the beginning of a line (either // the beginning of the string or just after a line feed), find the next // newline and position just after it. Debug.Assert(!_rightToLeft); int posm1 = pos - 1; if ((uint)posm1 < (uint)textSpan.Length && textSpan[posm1] != '\n') { int newline = textSpan.Slice(pos).IndexOf('\n'); if ((uint)newline > textSpan.Length - 1 - pos) { pos = textSpan.Length; return false; } // We've updated the position. Make sure there's still enough room in the input for a possible match. pos = newline + 1 + pos; if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } } switch (FindMode) { // There's an anchor. For some, we can simply compare against the current position. // For others, we can jump to the relevant location. case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: if (pos > 0) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: if (pos > start) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: if (pos < textSpan.Length - 1) { pos = textSpan.Length - 1; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: if (pos < textSpan.Length) { pos = textSpan.Length; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: if (pos > 0) { pos = 0; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: if (pos < start) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: if (pos < textSpan.Length - 1 || ((uint)pos < (uint)textSpan.Length && textSpan[pos] != '\n')) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: if (pos < textSpan.Length) { pos = 0; return false; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: if (pos < textSpan.Length - MinRequiredLength - 1) { pos = textSpan.Length - MinRequiredLength - 1; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: if (pos < textSpan.Length - MinRequiredLength) { pos = textSpan.Length - MinRequiredLength; } return true; // There's a case-sensitive prefix. Search for it with ordinal IndexOf. case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: { int i = textSpan.Slice(pos).IndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos = i + LeadingCaseSensitivePrefix.Length; return true; } pos = 0; return false; } // There's a literal at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos = i + 1; return true; } pos = 0; return false; } case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive: { char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (ti.ToLower(span[i]) == ch) { pos = i + 1; return true; } } pos = 0; return false; } // There's a set at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: { (char[]? chars, string set, _, _) = FixedDistanceSets![0]; ReadOnlySpan<char> span = textSpan.Slice(pos); if (chars is not null) { int i = span.IndexOfAny(chars); if (i >= 0) { pos += i; return true; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos += i; return true; } } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos); for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos += i; return true; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } // There's a literal at a fixed offset from the beginning of the pattern. Search for it. case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); int i = textSpan.Slice(pos + FixedDistanceLiteral.Distance).IndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos + FixedDistanceLiteral.Distance); for (int i = 0; i < span.Length; i++) { if (ti.ToLower(span[i]) == ch) { pos += i; return true; } } pos = textSpan.Length; return false; } // There are one or more sets at fixed offsets from the start of the pattern. case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (char[]? primaryChars, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); if (primaryChars is not null) { for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { int offset = inputPosition + primaryDistance; int index = textSpan.Slice(offset).IndexOfAny(primaryChars); if (index < 0) { break; } index += offset; // The index here will be offset indexed due to the use of span, so we add offset to get // real position on the string. inputPosition = index - primaryDistance; if (inputPosition > endMinusRequiredLength) { break; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; char c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(c, primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (_, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); TextInfo ti = _textInfo; ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(ti.ToLower(c), primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } pos = textSpan.Length; return false; } // There's a literal after a leading set loop. Find the literal, then walk backwards through the loop to find the starting position. case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: { Debug.Assert(LiteralAfterLoop is not null); (RegexNode loopNode, (char Char, string? String, char[]? Chars) literal) = LiteralAfterLoop.GetValueOrDefault(); Debug.Assert(loopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(loopNode.N == int.MaxValue); int startingPos = pos; while (true) { ReadOnlySpan<char> slice = textSpan.Slice(startingPos); // Find the literal. If we can't find it, we're done searching. int i = literal.String is not null ? slice.IndexOf(literal.String.AsSpan()) : literal.Chars is not null ? slice.IndexOfAny(literal.Chars.AsSpan()) : slice.IndexOf(literal.Char); if (i < 0) { break; } // We found the literal. Walk backwards from it finding as many matches as we can against the loop. int prev = i; while ((uint)--prev < (uint)slice.Length && RegexCharClass.CharInClass(slice[prev], loopNode.Str!, ref _asciiLookups![0])) ; // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. if ((i - prev - 1) < loopNode.M) { startingPos += i + 1; continue; } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate literalPos as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. This might only be feasible for RegexCompiler // and the source generator after we refactor them to generate a single Scan method rather than separate // FindFirstChar / Go methods. pos = startingPos + prev + 1; return true; } pos = textSpan.Length; return false; } // Nothing special to look for. Just return true indicating this is a valid position to try to match. default: Debug.Assert(FindMode == FindNextStartingPositionMode.NoSearch); return true; } } } /// <summary>Mode to use for searching for the next location of a possible match.</summary> internal enum FindNextStartingPositionMode { /// <summary>A "beginning" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Beginning, /// <summary>A "start" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Start, /// <summary>An "endz" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_EndZ, /// <summary>An "end" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_End, /// <summary>A "beginning" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Beginning, /// <summary>A "start" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Start, /// <summary>An "endz" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_EndZ, /// <summary>An "end" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_End, /// <summary>An "end" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_End, /// <summary>An "endz" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_EndZ, /// <summary>A case-sensitive multi-character substring at the beginning of the pattern.</summary> LeadingPrefix_LeftToRight_CaseSensitive, /// <summary>A case-sensitive multi-character substring at the beginning of the right-to-left pattern.</summary> LeadingPrefix_RightToLeft_CaseSensitive, /// <summary>A case-sensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseSensitive, /// <summary>A case-insensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseInsensitive, /// <summary>A case-sensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseSensitive, /// <summary>A case-insensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseInsensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-sensitive.</summary> FixedSets_LeftToRight_CaseSensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-insensitive.</summary> FixedSets_LeftToRight_CaseInsensitive, /// <summary>A literal after a non-overlapping set loop at the start of the pattern. The literal is case-sensitive.</summary> LiteralAfterLoop_LeftToRight_CaseSensitive, /// <summary>Nothing to search for. Nop.</summary> NoSearch, } }
1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.MultipleMatches.Tests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Threading.Tasks; using Xunit; using System.Linq; using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions.Tests { public class RegexMultipleMatchTests { [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Matches_MultipleCapturingGroups(RegexEngine engine) { string[] expectedGroupValues = { "abracadabra", "abra", "cad" }; string[] expectedGroupCaptureValues = { "abracad", "abra" }; // Another example - given by Brad Merril in an article on RegularExpressions Regex regex = await RegexHelpers.GetRegexAsync(engine, @"(abra(cad)?)+"); string input = "abracadabra1abracadabra2abracadabra3"; Match match = regex.Match(input); while (match.Success) { string expected = "abracadabra"; RegexAssert.Equal(expected, match); if (!RegexHelpers.IsNonBacktracking(engine)) { Assert.Equal(3, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { RegexAssert.Equal(expectedGroupValues[i], match.Groups[i]); if (i == 1) { Assert.Equal(2, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { RegexAssert.Equal(expectedGroupCaptureValues[j], match.Groups[i].Captures[j]); } } else if (i == 2) { Assert.Equal(1, match.Groups[i].Captures.Count); RegexAssert.Equal("cad", match.Groups[i].Captures[0]); } } Assert.Equal(1, match.Captures.Count); RegexAssert.Equal("abracadabra", match.Captures[0]); } match = match.NextMatch(); } } public static IEnumerable<object[]> Matches_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "[0-9]", "12345asdfasdfasdfljkhsda67890", RegexOptions.None, new CaptureData[] { new CaptureData("1", 0, 1), new CaptureData("2", 1, 1), new CaptureData("3", 2, 1), new CaptureData("4", 3, 1), new CaptureData("5", 4, 1), new CaptureData("6", 24, 1), new CaptureData("7", 25, 1), new CaptureData("8", 26, 1), new CaptureData("9", 27, 1), new CaptureData("0", 28, 1), } }; yield return new object[] { engine, "[a-z0-9]+", "[token1]? GARBAGEtoken2GARBAGE ;token3!", RegexOptions.None, new CaptureData[] { new CaptureData("token1", 1, 6), new CaptureData("token2", 17, 6), new CaptureData("token3", 32, 6) } }; yield return new object[] { engine, "(abc){2}", " !abcabcasl dkfjasiduf 12343214-//asdfjzpiouxoifzuoxpicvql23r\\` #$3245,2345278 :asdfas & 100% @daeeffga (ryyy27343) poiweurwabcabcasdfalksdhfaiuyoiruqwer{234}/[(132387 + x)]'aaa''?", RegexOptions.None, new CaptureData[] { new CaptureData("abcabc", 2, 6), new CaptureData("abcabc", 125, 6) } }; yield return new object[] { engine, @"\b\w*\b", "handling words of various lengths", RegexOptions.None, new CaptureData[] { new CaptureData("handling", 0, 8), new CaptureData("", 8, 0), new CaptureData("words", 9, 5), new CaptureData("", 14, 0), new CaptureData("of", 15, 2), new CaptureData("", 17, 0), new CaptureData("various", 18, 7), new CaptureData("", 25, 0), new CaptureData("lengths", 26, 7), new CaptureData("", 33, 0), } }; yield return new object[] { engine, @"\b\w{2}\b", "handling words of various lengths", RegexOptions.None, new CaptureData[] { new CaptureData("of", 15, 2), } }; yield return new object[] { engine, @"\w{6,}", "handling words of various lengths", RegexOptions.None, new CaptureData[] { new CaptureData("handling", 0, 8), new CaptureData("various", 18, 7), new CaptureData("lengths", 26, 7), } }; yield return new object[] { engine, "[a-z]", "a", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1) } }; yield return new object[] { engine, "[a-z]", "a1bc", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1), new CaptureData("b", 2, 1), new CaptureData("c", 3, 1) } }; yield return new object[] { engine, "(?:ab|cd|ef|gh|i)j", "abj cdj efj ghjij", RegexOptions.None, new CaptureData[] { new CaptureData("abj", 0, 3), new CaptureData("cdj", 7, 3), new CaptureData("efj", 12, 3), new CaptureData("ghj", 26, 3), new CaptureData("ij", 29, 2), } }; // Using ^ with multiline yield return new object[] { engine, "^", "", RegexOptions.Multiline, new[] { new CaptureData("", 0, 0) } }; yield return new object[] { engine, "^", "\n\n\n", RegexOptions.Multiline, new[] { new CaptureData("", 0, 0), new CaptureData("", 1, 0), new CaptureData("", 2, 0), new CaptureData("", 3, 0) } }; yield return new object[] { engine, "^abc", "abc\nabc \ndef abc \nab\nabc", RegexOptions.Multiline, new[] { new CaptureData("abc", 0, 3), new CaptureData("abc", 4, 3), new CaptureData("abc", 21, 3), } }; yield return new object[] { engine, @"^\w{5}", "abc\ndefg\n\nhijkl\n", RegexOptions.Multiline, new[] { new CaptureData("hijkl", 10, 5), } }; yield return new object[] { engine, @"^.*$", "abc\ndefg\n\nhijkl\n", RegexOptions.Multiline, new[] { new CaptureData("abc", 0, 3), new CaptureData("defg", 4, 4), new CaptureData("", 9, 0), new CaptureData("hijkl", 10, 5), new CaptureData("", 16, 0), } }; yield return new object[] { engine, ".*", "abc", RegexOptions.None, new[] { new CaptureData("abc", 0, 3), new CaptureData("", 3, 0) } }; if (!PlatformDetection.IsNetFramework) { // .NET Framework missing fix in https://github.com/dotnet/runtime/pull/1075 yield return new object[] { engine, @"[a -\-\b]", "a #.", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1), new CaptureData(" ", 1, 1), new CaptureData("#", 2, 1), } }; } if (!RegexHelpers.IsNonBacktracking(engine)) { yield return new object[] { engine, @"foo\d+", "0123456789foo4567890foo1foo 0987", RegexOptions.RightToLeft, new CaptureData[] { new CaptureData("foo1", 20, 4), new CaptureData("foo4567890", 10, 10), } }; yield return new object[] { engine, "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; yield return new object[] { engine, "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; yield return new object[] { engine, @"(?(\w+)\w+|)", "abcd", RegexOptions.None, new CaptureData[] { new CaptureData("abcd", 0, 4), new CaptureData("", 4, 0), } }; if (!PlatformDetection.IsNetFramework) { // .NET Framework has some behavioral inconsistencies when there's no else branch. yield return new object[] { engine, @"(?(\w+)\w+)", "abcd", RegexOptions.None, new CaptureData[] { new CaptureData("abcd", 0, 4), new CaptureData("", 4, 0), } }; } yield return new object[] { engine, @"^.*$", "abc\ndefg\n\nhijkl\n", RegexOptions.Multiline | RegexOptions.RightToLeft, new[] { new CaptureData("", 16, 0), new CaptureData("hijkl", 10, 5), new CaptureData("", 9, 0), new CaptureData("defg", 4, 4), new CaptureData("abc", 0, 3), } }; if (!PlatformDetection.IsNetFramework) { // .NET Framework missing fix in https://github.com/dotnet/runtime/pull/993 yield return new object[] { engine, "[^]", "every", RegexOptions.ECMAScript, new CaptureData[] { new CaptureData("e", 0, 1), new CaptureData("v", 1, 1), new CaptureData("e", 2, 1), new CaptureData("r", 3, 1), new CaptureData("y", 4, 1), } }; } } #if !NETFRAMEWORK // these tests currently fail on .NET Framework, and we need to check IsDynamicCodeCompiled but that doesn't exist on .NET Framework if (engine != RegexEngine.Interpreter && // these tests currently fail with RegexInterpreter RuntimeFeature.IsDynamicCodeCompiled) // if dynamic code isn't compiled, RegexOptions.Compiled falls back to the interpreter, for which these tests currently fail { // Fails on interpreter and .NET Framework: [ActiveIssue("https://github.com/dotnet/runtime/issues/62094")] yield return new object[] { engine, "@(a*)+?", "@", RegexOptions.None, new[] { new CaptureData("@", 0, 1) } }; // Fails on interpreter and .NET Framework: [ActiveIssue("https://github.com/dotnet/runtime/issues/62094")] yield return new object[] { engine, @"(?:){93}", "x", RegexOptions.None, new[] { new CaptureData("", 0, 0), new CaptureData("", 1, 0) } }; if (!RegexHelpers.IsNonBacktracking(engine)) // atomic subexpressions aren't supported { // Fails on interpreter and .NET Framework: [ActiveIssue("https://github.com/dotnet/runtime/issues/62094")] yield return new object[] { engine, @"()(?>\1+?).\b", "xxxx", RegexOptions.None, new[] { new CaptureData("x", 3, 1), } }; } } #endif } } [Theory] [MemberData(nameof(Matches_TestData))] public async Task Matches(RegexEngine engine, string pattern, string input, RegexOptions options, CaptureData[] expected) { Regex regexAdvanced = await RegexHelpers.GetRegexAsync(engine, pattern, options); VerifyMatches(regexAdvanced.Matches(input), expected); VerifyMatches(regexAdvanced.Match(input), expected); } private static void VerifyMatches(Match match, CaptureData[] expected) { for (int i = 0; match.Success; i++, match = match.NextMatch()) { VerifyMatch(match, expected[i]); } } private static void VerifyMatches(MatchCollection matches, CaptureData[] expected) { Assert.Equal(expected.Length, matches.Count); for (int i = 0; i < matches.Count; i++) { VerifyMatch(matches[i], expected[i]); } } private static void VerifyMatch(Match match, CaptureData expected) { Assert.True(match.Success); Assert.Equal(expected.Index, match.Index); Assert.Equal(expected.Length, match.Length); RegexAssert.Equal(expected.Value, match); Assert.Equal(expected.Index, match.Groups[0].Index); Assert.Equal(expected.Length, match.Groups[0].Length); RegexAssert.Equal(expected.Value, match.Groups[0]); Assert.Equal(1, match.Captures.Count); Assert.Equal(expected.Index, match.Captures[0].Index); Assert.Equal(expected.Length, match.Captures[0].Length); RegexAssert.Equal(expected.Value, match.Captures[0]); } [Fact] public void Matches_Invalid() { // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Options are invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1), TimeSpan.FromSeconds(1))); // 0x400 is new NonBacktracking mode that is now valid, 0x800 is still invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x800)); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x800, TimeSpan.FromSeconds(1))); // MatchTimeout is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); // Start is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", 6)); } [Fact] public void NextMatch_EmptyMatch_ReturnsEmptyMatch() { Assert.Same(Match.Empty, Match.Empty.NextMatch()); } } }
// 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.Tasks; using Xunit; using System.Linq; using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions.Tests { public class RegexMultipleMatchTests { [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Matches_MultipleCapturingGroups(RegexEngine engine) { string[] expectedGroupValues = { "abracadabra", "abra", "cad" }; string[] expectedGroupCaptureValues = { "abracad", "abra" }; // Another example - given by Brad Merril in an article on RegularExpressions Regex regex = await RegexHelpers.GetRegexAsync(engine, @"(abra(cad)?)+"); string input = "abracadabra1abracadabra2abracadabra3"; Match match = regex.Match(input); while (match.Success) { string expected = "abracadabra"; RegexAssert.Equal(expected, match); if (!RegexHelpers.IsNonBacktracking(engine)) { Assert.Equal(3, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { RegexAssert.Equal(expectedGroupValues[i], match.Groups[i]); if (i == 1) { Assert.Equal(2, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { RegexAssert.Equal(expectedGroupCaptureValues[j], match.Groups[i].Captures[j]); } } else if (i == 2) { Assert.Equal(1, match.Groups[i].Captures.Count); RegexAssert.Equal("cad", match.Groups[i].Captures[0]); } } Assert.Equal(1, match.Captures.Count); RegexAssert.Equal("abracadabra", match.Captures[0]); } match = match.NextMatch(); } } public static IEnumerable<object[]> Matches_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "[0-9]", "12345asdfasdfasdfljkhsda67890", RegexOptions.None, new CaptureData[] { new CaptureData("1", 0, 1), new CaptureData("2", 1, 1), new CaptureData("3", 2, 1), new CaptureData("4", 3, 1), new CaptureData("5", 4, 1), new CaptureData("6", 24, 1), new CaptureData("7", 25, 1), new CaptureData("8", 26, 1), new CaptureData("9", 27, 1), new CaptureData("0", 28, 1), } }; yield return new object[] { engine, "[a-z0-9]+", "[token1]? GARBAGEtoken2GARBAGE ;token3!", RegexOptions.None, new CaptureData[] { new CaptureData("token1", 1, 6), new CaptureData("token2", 17, 6), new CaptureData("token3", 32, 6) } }; yield return new object[] { engine, "(abc){2}", " !abcabcasl dkfjasiduf 12343214-//asdfjzpiouxoifzuoxpicvql23r\\` #$3245,2345278 :asdfas & 100% @daeeffga (ryyy27343) poiweurwabcabcasdfalksdhfaiuyoiruqwer{234}/[(132387 + x)]'aaa''?", RegexOptions.None, new CaptureData[] { new CaptureData("abcabc", 2, 6), new CaptureData("abcabc", 125, 6) } }; yield return new object[] { engine, @"\b\w*\b", "handling words of various lengths", RegexOptions.None, new CaptureData[] { new CaptureData("handling", 0, 8), new CaptureData("", 8, 0), new CaptureData("words", 9, 5), new CaptureData("", 14, 0), new CaptureData("of", 15, 2), new CaptureData("", 17, 0), new CaptureData("various", 18, 7), new CaptureData("", 25, 0), new CaptureData("lengths", 26, 7), new CaptureData("", 33, 0), } }; yield return new object[] { engine, @"\b\w{2}\b", "handling words of various lengths", RegexOptions.None, new CaptureData[] { new CaptureData("of", 15, 2), } }; yield return new object[] { engine, @"\w{6,}", "handling words of various lengths", RegexOptions.None, new CaptureData[] { new CaptureData("handling", 0, 8), new CaptureData("various", 18, 7), new CaptureData("lengths", 26, 7), } }; yield return new object[] { engine, "[a-z]", "a", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1) } }; yield return new object[] { engine, "[a-z]", "a1bc", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1), new CaptureData("b", 2, 1), new CaptureData("c", 3, 1) } }; yield return new object[] { engine, "(?:ab|cd|ef|gh|i)j", "abj cdj efj ghjij", RegexOptions.None, new CaptureData[] { new CaptureData("abj", 0, 3), new CaptureData("cdj", 7, 3), new CaptureData("efj", 12, 3), new CaptureData("ghj", 26, 3), new CaptureData("ij", 29, 2), } }; // Using ^ and $ with multiline yield return new object[] { engine, "^", "", RegexOptions.Multiline, new[] { new CaptureData("", 0, 0) } }; yield return new object[] { engine, "^", "\n\n\n", RegexOptions.Multiline, new[] { new CaptureData("", 0, 0), new CaptureData("", 1, 0), new CaptureData("", 2, 0), new CaptureData("", 3, 0) } }; yield return new object[] { engine, "^abc", "abc\nabc \ndef abc \nab\nabc", RegexOptions.Multiline, new[] { new CaptureData("abc", 0, 3), new CaptureData("abc", 4, 3), new CaptureData("abc", 21, 3), } }; yield return new object[] { engine, @"^\w{5}", "abc\ndefg\n\nhijkl\n", RegexOptions.Multiline, new[] { new CaptureData("hijkl", 10, 5), } }; yield return new object[] { engine, @"^.*$", "abc\ndefg\n\nhijkl\n", RegexOptions.Multiline, new[] { new CaptureData("abc", 0, 3), new CaptureData("defg", 4, 4), new CaptureData("", 9, 0), new CaptureData("hijkl", 10, 5), new CaptureData("", 16, 0), } }; yield return new object[] { engine, ".*", "abc", RegexOptions.None, new[] { new CaptureData("abc", 0, 3), new CaptureData("", 3, 0) } }; yield return new object[] { engine, @"^[^a]a", "bar\n", RegexOptions.Multiline, new[] { new CaptureData("ba", 0, 2) } }; yield return new object[] { engine, @"^[^a]a", "car\nbar\n", RegexOptions.Multiline, new[] { new CaptureData("ca", 0, 2), new CaptureData("ba", 4, 2) } }; yield return new object[] { engine, @"[0-9]cat$", "1cat\n2cat", RegexOptions.Multiline, new[] { new CaptureData("1cat", 0, 4), new CaptureData("2cat", 5, 4) } }; if (!PlatformDetection.IsNetFramework) { // .NET Framework missing fix in https://github.com/dotnet/runtime/pull/1075 yield return new object[] { engine, @"[a -\-\b]", "a #.", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1), new CaptureData(" ", 1, 1), new CaptureData("#", 2, 1), } }; } if (!RegexHelpers.IsNonBacktracking(engine)) { yield return new object[] { engine, @"foo\d+", "0123456789foo4567890foo1foo 0987", RegexOptions.RightToLeft, new CaptureData[] { new CaptureData("foo1", 20, 4), new CaptureData("foo4567890", 10, 10), } }; yield return new object[] { engine, "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; yield return new object[] { engine, "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; yield return new object[] { engine, @"(?(\w+)\w+|)", "abcd", RegexOptions.None, new CaptureData[] { new CaptureData("abcd", 0, 4), new CaptureData("", 4, 0), } }; if (!PlatformDetection.IsNetFramework) { // .NET Framework has some behavioral inconsistencies when there's no else branch. yield return new object[] { engine, @"(?(\w+)\w+)", "abcd", RegexOptions.None, new CaptureData[] { new CaptureData("abcd", 0, 4), new CaptureData("", 4, 0), } }; } yield return new object[] { engine, @"^.*$", "abc\ndefg\n\nhijkl\n", RegexOptions.Multiline | RegexOptions.RightToLeft, new[] { new CaptureData("", 16, 0), new CaptureData("hijkl", 10, 5), new CaptureData("", 9, 0), new CaptureData("defg", 4, 4), new CaptureData("abc", 0, 3), } }; if (!PlatformDetection.IsNetFramework) { // .NET Framework missing fix in https://github.com/dotnet/runtime/pull/993 yield return new object[] { engine, "[^]", "every", RegexOptions.ECMAScript, new CaptureData[] { new CaptureData("e", 0, 1), new CaptureData("v", 1, 1), new CaptureData("e", 2, 1), new CaptureData("r", 3, 1), new CaptureData("y", 4, 1), } }; } } #if !NETFRAMEWORK // these tests currently fail on .NET Framework, and we need to check IsDynamicCodeCompiled but that doesn't exist on .NET Framework if (engine != RegexEngine.Interpreter && // these tests currently fail with RegexInterpreter RuntimeFeature.IsDynamicCodeCompiled) // if dynamic code isn't compiled, RegexOptions.Compiled falls back to the interpreter, for which these tests currently fail { // Fails on interpreter and .NET Framework: [ActiveIssue("https://github.com/dotnet/runtime/issues/62094")] yield return new object[] { engine, "@(a*)+?", "@", RegexOptions.None, new[] { new CaptureData("@", 0, 1) } }; // Fails on interpreter and .NET Framework: [ActiveIssue("https://github.com/dotnet/runtime/issues/62094")] yield return new object[] { engine, @"(?:){93}", "x", RegexOptions.None, new[] { new CaptureData("", 0, 0), new CaptureData("", 1, 0) } }; if (!RegexHelpers.IsNonBacktracking(engine)) // atomic subexpressions aren't supported { // Fails on interpreter and .NET Framework: [ActiveIssue("https://github.com/dotnet/runtime/issues/62094")] yield return new object[] { engine, @"()(?>\1+?).\b", "xxxx", RegexOptions.None, new[] { new CaptureData("x", 3, 1), } }; } } #endif } } [Theory] [MemberData(nameof(Matches_TestData))] public async Task Matches(RegexEngine engine, string pattern, string input, RegexOptions options, CaptureData[] expected) { Regex regexAdvanced = await RegexHelpers.GetRegexAsync(engine, pattern, options); VerifyMatches(regexAdvanced.Matches(input), expected); VerifyMatches(regexAdvanced.Match(input), expected); } private static void VerifyMatches(Match match, CaptureData[] expected) { for (int i = 0; match.Success; i++, match = match.NextMatch()) { VerifyMatch(match, expected[i]); } } private static void VerifyMatches(MatchCollection matches, CaptureData[] expected) { Assert.Equal(expected.Length, matches.Count); for (int i = 0; i < matches.Count; i++) { VerifyMatch(matches[i], expected[i]); } } private static void VerifyMatch(Match match, CaptureData expected) { Assert.True(match.Success); Assert.Equal(expected.Index, match.Index); Assert.Equal(expected.Length, match.Length); RegexAssert.Equal(expected.Value, match); Assert.Equal(expected.Index, match.Groups[0].Index); Assert.Equal(expected.Length, match.Groups[0].Length); RegexAssert.Equal(expected.Value, match.Groups[0]); Assert.Equal(1, match.Captures.Count); Assert.Equal(expected.Index, match.Captures[0].Index); Assert.Equal(expected.Length, match.Captures[0].Length); RegexAssert.Equal(expected.Value, match.Captures[0]); } [Fact] public void Matches_Invalid() { // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Options are invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1), TimeSpan.FromSeconds(1))); // 0x400 is new NonBacktracking mode that is now valid, 0x800 is still invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x800)); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x800, TimeSpan.FromSeconds(1))); // MatchTimeout is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); // Start is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", 6)); } [Fact] public void NextMatch_EmptyMatch_ReturnsEmptyMatch() { Assert.Same(Match.Empty, Match.Empty.NextMatch()); } } }
1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/tests/JIT/Methodical/refany/stress1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace JitTest { using System; internal class StressTest { private const int ITERATIONS = 2000; private const ulong MAGIC = 0x7700001492000077; private static ulong UnpackRef(TypedReference _ref, int iterCount) { if (iterCount++ == ITERATIONS) { Console.WriteLine(ITERATIONS.ToString() + " refs unpacked."); if (__refvalue(_ref, ulong) == MAGIC) { Console.WriteLine("Passed."); throw new ArgumentException(); //cleanup in an unusual way } else { Console.WriteLine("failed."); throw new Exception(); } } else return __refvalue(_ref, ulong); } private static void PackRef(TypedReference _ref, int iterCount) { if (++iterCount == ITERATIONS) { Console.WriteLine(ITERATIONS.ToString() + " refs packed."); UnpackRef(_ref, iterCount); } else { ulong N = UnpackRef(_ref, 0); PackRef(__makeref(N), iterCount); } } private static int Main() { try { ulong N = MAGIC; PackRef(__makeref(N), 0); return 2; } catch (ArgumentException) { return 100; } catch (Exception) { return 1; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace JitTest { using System; internal class StressTest { private const int ITERATIONS = 2000; private const ulong MAGIC = 0x7700001492000077; private static ulong UnpackRef(TypedReference _ref, int iterCount) { if (iterCount++ == ITERATIONS) { Console.WriteLine(ITERATIONS.ToString() + " refs unpacked."); if (__refvalue(_ref, ulong) == MAGIC) { Console.WriteLine("Passed."); throw new ArgumentException(); //cleanup in an unusual way } else { Console.WriteLine("failed."); throw new Exception(); } } else return __refvalue(_ref, ulong); } private static void PackRef(TypedReference _ref, int iterCount) { if (++iterCount == ITERATIONS) { Console.WriteLine(ITERATIONS.ToString() + " refs packed."); UnpackRef(_ref, iterCount); } else { ulong N = UnpackRef(_ref, 0); PackRef(__makeref(N), iterCount); } } private static int Main() { try { ulong N = MAGIC; PackRef(__makeref(N), 0); return 2; } catch (ArgumentException) { return 100; } catch (Exception) { return 1; } } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; namespace System.Composition.Diagnostics { internal static class CompositionTrace { public static void Registration_ConstructorConventionOverridden(Type type) { if (type == null) throw new Exception(SR.Diagnostic_InternalExceptionMessage); if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Registration_ConstructorConventionOverridden, SR.Registration_ConstructorConventionOverridden, type.FullName); } } public static void Registration_TypeExportConventionOverridden(Type type) { if (type == null) throw new Exception(SR.Diagnostic_InternalExceptionMessage); if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_TypeExportConventionOverridden, SR.Registration_TypeExportConventionOverridden, type.FullName); } } public static void Registration_MemberExportConventionOverridden(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberExportConventionOverridden, SR.Registration_MemberExportConventionOverridden, member.Name, type.FullName); } } public static void Registration_MemberImportConventionOverridden(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionOverridden, SR.Registration_MemberImportConventionOverridden, member.Name, type.FullName); } } public static void Registration_OnSatisfiedImportNotificationOverridden(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_OnSatisfiedImportNotificationOverridden, SR.Registration_OnSatisfiedImportNotificationOverridden, member.Name, type.FullName); } } public static void Registration_PartCreationConventionOverridden(Type type!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartCreationConventionOverridden, SR.Registration_PartCreationConventionOverridden, type.FullName); } } public static void Registration_MemberImportConventionMatchedTwice(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionMatchedTwice, SR.Registration_MemberImportConventionMatchedTwice, member.Name, type.FullName); } } public static void Registration_PartMetadataConventionOverridden(Type type!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartMetadataConventionOverridden, SR.Registration_PartMetadataConventionOverridden, type.FullName); } } public static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter!!, ConstructorInfo constructor!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_ParameterImportConventionOverridden, SR.Registration_ParameterImportConventionOverridden, parameter.Name, constructor.Name); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; namespace System.Composition.Diagnostics { internal static class CompositionTrace { public static void Registration_ConstructorConventionOverridden(Type type) { if (type == null) throw new Exception(SR.Diagnostic_InternalExceptionMessage); if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Registration_ConstructorConventionOverridden, SR.Registration_ConstructorConventionOverridden, type.FullName); } } public static void Registration_TypeExportConventionOverridden(Type type) { if (type == null) throw new Exception(SR.Diagnostic_InternalExceptionMessage); if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_TypeExportConventionOverridden, SR.Registration_TypeExportConventionOverridden, type.FullName); } } public static void Registration_MemberExportConventionOverridden(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberExportConventionOverridden, SR.Registration_MemberExportConventionOverridden, member.Name, type.FullName); } } public static void Registration_MemberImportConventionOverridden(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionOverridden, SR.Registration_MemberImportConventionOverridden, member.Name, type.FullName); } } public static void Registration_OnSatisfiedImportNotificationOverridden(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_OnSatisfiedImportNotificationOverridden, SR.Registration_OnSatisfiedImportNotificationOverridden, member.Name, type.FullName); } } public static void Registration_PartCreationConventionOverridden(Type type!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartCreationConventionOverridden, SR.Registration_PartCreationConventionOverridden, type.FullName); } } public static void Registration_MemberImportConventionMatchedTwice(Type type!!, MemberInfo member!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionMatchedTwice, SR.Registration_MemberImportConventionMatchedTwice, member.Name, type.FullName); } } public static void Registration_PartMetadataConventionOverridden(Type type!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartMetadataConventionOverridden, SR.Registration_PartMetadataConventionOverridden, type.FullName); } } public static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter!!, ConstructorInfo constructor!!) { if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_ParameterImportConventionOverridden, SR.Registration_ParameterImportConventionOverridden, parameter.Name, constructor.Name); } } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/tests/JIT/HardwareIntrinsics/Arm/Sha256/HashUpdate1.Vector128.UInt32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void HashUpdate1_Vector128_UInt32() { var test = new SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public Vector128<UInt32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } 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] = 0x44556677; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32 testClass) { var result = Sha256.HashUpdate1(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) fixed (Vector128<UInt32>* pFld3 = &_fld3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), AdvSimd.LoadVector128((UInt32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op3ElementCount = 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 UInt32[] _data3 = new UInt32[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private static Vector128<UInt32> _clsVar3; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private Vector128<UInt32> _fld3; private DataTable _dataTable; static SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } 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] = 0x44556677; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } 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] = 0x44556677; } 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 < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 0x44556677; } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } _dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sha256.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sha256.HashUpdate1( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sha256).GetMethod(nameof(Sha256.HashUpdate1), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sha256).GetMethod(nameof(Sha256.HashUpdate1), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sha256.HashUpdate1( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) fixed (Vector128<UInt32>* pClsVar3 = &_clsVar3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt32*)(pClsVar2)), AdvSimd.LoadVector128((UInt32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr); var result = Sha256.HashUpdate1(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)); var result = Sha256.HashUpdate1(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32(); var result = Sha256.HashUpdate1(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) fixed (Vector128<UInt32>* pFld3 = &test._fld3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), AdvSimd.LoadVector128((UInt32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sha256.HashUpdate1(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) fixed (Vector128<UInt32>* pFld3 = &_fld3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), AdvSimd.LoadVector128((UInt32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sha256.HashUpdate1(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt32*)(&test._fld2)), AdvSimd.LoadVector128((UInt32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector128<UInt32> op2, Vector128<UInt32> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (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, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] secondOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; UInt32[] expectedResult = new UInt32[]{0x3D22118E, 0x987CA5FB, 0x54F4E477, 0xDFB50278}; for (int i = 0; i < RetElementCount; i++) { if (result[i] != expectedResult[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sha256)}.{nameof(Sha256.HashUpdate1)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void HashUpdate1_Vector128_UInt32() { var test = new SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public Vector128<UInt32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } 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] = 0x44556677; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32 testClass) { var result = Sha256.HashUpdate1(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) fixed (Vector128<UInt32>* pFld3 = &_fld3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), AdvSimd.LoadVector128((UInt32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op3ElementCount = 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 UInt32[] _data3 = new UInt32[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private static Vector128<UInt32> _clsVar3; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private Vector128<UInt32> _fld3; private DataTable _dataTable; static SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } 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] = 0x44556677; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } 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] = 0x44556677; } 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 < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 0x44556677; } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; } _dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sha256.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sha256.HashUpdate1( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sha256).GetMethod(nameof(Sha256.HashUpdate1), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sha256).GetMethod(nameof(Sha256.HashUpdate1), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sha256.HashUpdate1( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) fixed (Vector128<UInt32>* pClsVar3 = &_clsVar3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt32*)(pClsVar2)), AdvSimd.LoadVector128((UInt32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr); var result = Sha256.HashUpdate1(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)); var result = Sha256.HashUpdate1(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32(); var result = Sha256.HashUpdate1(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SecureHashTernaryOpTest__HashUpdate1_Vector128_UInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) fixed (Vector128<UInt32>* pFld3 = &test._fld3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), AdvSimd.LoadVector128((UInt32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sha256.HashUpdate1(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) fixed (Vector128<UInt32>* pFld3 = &_fld3) { var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), AdvSimd.LoadVector128((UInt32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sha256.HashUpdate1(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sha256.HashUpdate1( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt32*)(&test._fld2)), AdvSimd.LoadVector128((UInt32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector128<UInt32> op2, Vector128<UInt32> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (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, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] secondOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; UInt32[] expectedResult = new UInt32[]{0x3D22118E, 0x987CA5FB, 0x54F4E477, 0xDFB50278}; for (int i = 0; i < RetElementCount; i++) { if (result[i] != expectedResult[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sha256)}.{nameof(Sha256.HashUpdate1)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.Forwards.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.IO.UnmanagedMemoryStream))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.CriticalHandle))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandle))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandleType))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.InAttribute))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.SafeBuffer))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.SafeHandle))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.UnmanagedType))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.Missing))]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.IO.UnmanagedMemoryStream))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.CriticalHandle))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandle))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandleType))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.InAttribute))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.SafeBuffer))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.SafeHandle))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.UnmanagedType))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.Missing))]
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.COMWrappers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Drawing.Internal; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System.Drawing { public sealed partial class Icon : MarshalByRefObject, ICloneable, IDisposable, ISerializable { public unsafe void Save(Stream outputStream) { if (_iconData != null) { outputStream.Write(_iconData, 0, _iconData.Length); } else { if (outputStream == null) throw new ArgumentNullException(nameof(outputStream)); // Ideally, we would pick apart the icon using // GetIconInfo, and then pull the individual bitmaps out, // converting them to DIBS and saving them into the file. // But, in the interest of simplicity, we just call to // OLE to do it for us. PICTDESC pictdesc = PICTDESC.CreateIconPICTDESC(Handle); Guid iid = DrawingCom.IPicture.IID; IntPtr lpPicture; Marshal.ThrowExceptionForHR(OleCreatePictureIndirect(&pictdesc, &iid, fOwn: 0, &lpPicture)); IntPtr streamPtr = IntPtr.Zero; try { // Use UniqueInstance here because we never want to cache the wrapper. It only gets used once and then disposed. using DrawingCom.IPicture picture = (DrawingCom.IPicture)DrawingCom.Instance .GetOrCreateObjectForComInstance(lpPicture, CreateObjectFlags.UniqueInstance); var gpStream = new GPStream(outputStream, makeSeekable: false); streamPtr = DrawingCom.Instance.GetOrCreateComInterfaceForObject(gpStream, CreateComInterfaceFlags.None); DrawingCom.ThrowExceptionForHR(picture.SaveAsFile(streamPtr, -1, null)); } finally { if (streamPtr != IntPtr.Zero) { int count = Marshal.Release(streamPtr); Debug.Assert(count == 0); } if (lpPicture != IntPtr.Zero) { int count = Marshal.Release(lpPicture); Debug.Assert(count == 0); } } } } [GeneratedDllImport(Interop.Libraries.Oleaut32)] private static unsafe partial int OleCreatePictureIndirect(PICTDESC* pictdesc, Guid* refiid, int fOwn, IntPtr* lplpvObj); [StructLayout(LayoutKind.Sequential)] private readonly struct PICTDESC { public readonly int SizeOfStruct; public readonly int PicType; public readonly IntPtr Icon; private unsafe PICTDESC(int picType, IntPtr hicon) { SizeOfStruct = sizeof(PICTDESC); PicType = picType; Icon = hicon; } public static PICTDESC CreateIconPICTDESC(IntPtr hicon) => new PICTDESC(Ole.PICTYPE_ICON, hicon); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Drawing.Internal; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System.Drawing { public sealed partial class Icon : MarshalByRefObject, ICloneable, IDisposable, ISerializable { public unsafe void Save(Stream outputStream) { if (_iconData != null) { outputStream.Write(_iconData, 0, _iconData.Length); } else { if (outputStream == null) throw new ArgumentNullException(nameof(outputStream)); // Ideally, we would pick apart the icon using // GetIconInfo, and then pull the individual bitmaps out, // converting them to DIBS and saving them into the file. // But, in the interest of simplicity, we just call to // OLE to do it for us. PICTDESC pictdesc = PICTDESC.CreateIconPICTDESC(Handle); Guid iid = DrawingCom.IPicture.IID; IntPtr lpPicture; Marshal.ThrowExceptionForHR(OleCreatePictureIndirect(&pictdesc, &iid, fOwn: 0, &lpPicture)); IntPtr streamPtr = IntPtr.Zero; try { // Use UniqueInstance here because we never want to cache the wrapper. It only gets used once and then disposed. using DrawingCom.IPicture picture = (DrawingCom.IPicture)DrawingCom.Instance .GetOrCreateObjectForComInstance(lpPicture, CreateObjectFlags.UniqueInstance); var gpStream = new GPStream(outputStream, makeSeekable: false); streamPtr = DrawingCom.Instance.GetOrCreateComInterfaceForObject(gpStream, CreateComInterfaceFlags.None); DrawingCom.ThrowExceptionForHR(picture.SaveAsFile(streamPtr, -1, null)); } finally { if (streamPtr != IntPtr.Zero) { int count = Marshal.Release(streamPtr); Debug.Assert(count == 0); } if (lpPicture != IntPtr.Zero) { int count = Marshal.Release(lpPicture); Debug.Assert(count == 0); } } } } [GeneratedDllImport(Interop.Libraries.Oleaut32)] private static unsafe partial int OleCreatePictureIndirect(PICTDESC* pictdesc, Guid* refiid, int fOwn, IntPtr* lplpvObj); [StructLayout(LayoutKind.Sequential)] private readonly struct PICTDESC { public readonly int SizeOfStruct; public readonly int PicType; public readonly IntPtr Icon; private unsafe PICTDESC(int picType, IntPtr hicon) { SizeOfStruct = sizeof(PICTDESC); PicType = picType; Icon = hicon; } public static PICTDESC CreateIconPICTDESC(IntPtr hicon) => new PICTDESC(Ole.PICTYPE_ICON, hicon); } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/op_Addition.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_AdditionByte() { var test = new VectorBinaryOpTest__op_AdditionByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__op_AdditionByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_AdditionByte testClass) { var result = _fld1 + _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_AdditionByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public VectorBinaryOpTest__op_AdditionByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr) + Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector64<Byte>).GetMethod("op_Addition", new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 + _clsVar2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = op1 + op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_AdditionByte(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 + _fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(left[0] + right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(left[i] + right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Addition<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_AdditionByte() { var test = new VectorBinaryOpTest__op_AdditionByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__op_AdditionByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_AdditionByte testClass) { var result = _fld1 + _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_AdditionByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public VectorBinaryOpTest__op_AdditionByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr) + Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector64<Byte>).GetMethod("op_Addition", new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 + _clsVar2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = op1 + op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_AdditionByte(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 + _fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(left[0] + right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(left[i] + right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Addition<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Speech/src/Internal/Synthesis/AudioFileOut.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Speech.AudioFormat; using System.Threading; namespace System.Speech.Internal.Synthesis { /// <summary> /// Encapsulates Waveform Audio Interface playback functions and provides a simple /// interface for playing audio. /// </summary> internal class AudioFileOut : AudioBase, IDisposable { #region Constructors /// <summary> /// Create an instance of AudioFileOut. /// </summary> internal AudioFileOut(Stream stream, SpeechAudioFormatInfo formatInfo, bool headerInfo, IAsyncDispatch asyncDispatch) { _asyncDispatch = asyncDispatch; _stream = stream; _startStreamPosition = _stream.Position; _hasHeader = headerInfo; _wfxOut = new WAVEFORMATEX(); // if we have a formatInfo object, format conversion may be necessary if (formatInfo != null) { // Build the Wave format from the formatInfo _wfxOut.wFormatTag = (short)formatInfo.EncodingFormat; _wfxOut.wBitsPerSample = (short)formatInfo.BitsPerSample; _wfxOut.nSamplesPerSec = formatInfo.SamplesPerSecond; _wfxOut.nChannels = (short)formatInfo.ChannelCount; } else { // Set the default values _wfxOut = WAVEFORMATEX.Default; } _wfxOut.nBlockAlign = (short)(_wfxOut.nChannels * _wfxOut.wBitsPerSample / 8); _wfxOut.nAvgBytesPerSec = _wfxOut.wBitsPerSample * _wfxOut.nSamplesPerSec * _wfxOut.nChannels / 8; } public void Dispose() { _evt.Close(); GC.SuppressFinalize(this); } #endregion #region Internal Methods /// <summary> /// Begin to play /// </summary> internal override void Begin(byte[] wfx) { if (_deviceOpen) { System.Diagnostics.Debug.Assert(false); throw new InvalidOperationException(); } // Get the audio format if conversion is needed _wfxIn = WAVEFORMATEX.ToWaveHeader(wfx); _doConversion = _pcmConverter.PrepareConverter(ref _wfxIn, ref _wfxOut); if (_totalByteWrittens == 0 && _hasHeader) { WriteWaveHeader(_stream, _wfxOut, _startStreamPosition, 0); } _bytesWritten = 0; // set the flags _aborted = false; _deviceOpen = true; } /// <summary> /// Begin to play /// </summary> internal override void End() { if (!_deviceOpen) { System.Diagnostics.Debug.Assert(false); throw new InvalidOperationException(); } _deviceOpen = false; if (!_aborted) { if (_hasHeader) { long position = _stream.Position; WriteWaveHeader(_stream, _wfxOut, _startStreamPosition, _totalByteWrittens); _stream.Seek(position, SeekOrigin.Begin); } } } #region AudioDevice implementation /// <summary> /// Play a wave file. /// </summary> internal override void Play(byte[] buffer) { if (!_deviceOpen) { System.Diagnostics.Debug.Assert(false); } else { byte[] abOut = _doConversion ? _pcmConverter.ConvertSamples(buffer) : buffer; if (_paused) { _evt.WaitOne(); _evt.Reset(); } if (!_aborted) { _stream.Write(abOut, 0, abOut.Length); _totalByteWrittens += abOut.Length; _bytesWritten += abOut.Length; } } } /// <summary> /// Pause the playback of a sound. /// </summary> internal override void Pause() { if (!_aborted && !_paused) { lock (_noWriteOutLock) { _paused = true; } } } /// <summary> /// Resume the playback of a paused sound. /// </summary> internal override void Resume() { if (!_aborted && _paused) { lock (_noWriteOutLock) { _paused = false; _evt.Set(); } } } /// <summary> /// Wait for all the queued buffers to be played /// </summary> internal override void Abort() { lock (_noWriteOutLock) { _aborted = true; _paused = false; _evt.Set(); } } internal override void InjectEvent(TTSEvent ttsEvent) { if (!_aborted && _asyncDispatch != null) { _asyncDispatch.Post(ttsEvent); } } /// <summary> /// File operation are basically synchronous /// </summary> internal override void WaitUntilDone() { lock (_noWriteOutLock) { } } #endregion #endregion #region Internal Fields internal override TimeSpan Duration { get { if (_wfxIn.nAvgBytesPerSec == 0) { return new TimeSpan(0); } return new TimeSpan((_bytesWritten * TimeSpan.TicksPerSecond) / _wfxIn.nAvgBytesPerSec); } } internal override long Position { get { return _stream.Position; } } internal override byte[] WaveFormat { get { return _wfxOut.ToBytes(); } } #endregion #region Private Fields protected ManualResetEvent _evt = new(false); protected bool _deviceOpen; protected Stream _stream; protected PcmConverter _pcmConverter = new(); protected bool _doConversion; protected bool _paused; protected int _totalByteWrittens; protected int _bytesWritten; #endregion #region Private Fields private IAsyncDispatch _asyncDispatch; private object _noWriteOutLock = new(); private WAVEFORMATEX _wfxIn; private WAVEFORMATEX _wfxOut; private bool _hasHeader; private long _startStreamPosition; #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.IO; using System.Speech.AudioFormat; using System.Threading; namespace System.Speech.Internal.Synthesis { /// <summary> /// Encapsulates Waveform Audio Interface playback functions and provides a simple /// interface for playing audio. /// </summary> internal class AudioFileOut : AudioBase, IDisposable { #region Constructors /// <summary> /// Create an instance of AudioFileOut. /// </summary> internal AudioFileOut(Stream stream, SpeechAudioFormatInfo formatInfo, bool headerInfo, IAsyncDispatch asyncDispatch) { _asyncDispatch = asyncDispatch; _stream = stream; _startStreamPosition = _stream.Position; _hasHeader = headerInfo; _wfxOut = new WAVEFORMATEX(); // if we have a formatInfo object, format conversion may be necessary if (formatInfo != null) { // Build the Wave format from the formatInfo _wfxOut.wFormatTag = (short)formatInfo.EncodingFormat; _wfxOut.wBitsPerSample = (short)formatInfo.BitsPerSample; _wfxOut.nSamplesPerSec = formatInfo.SamplesPerSecond; _wfxOut.nChannels = (short)formatInfo.ChannelCount; } else { // Set the default values _wfxOut = WAVEFORMATEX.Default; } _wfxOut.nBlockAlign = (short)(_wfxOut.nChannels * _wfxOut.wBitsPerSample / 8); _wfxOut.nAvgBytesPerSec = _wfxOut.wBitsPerSample * _wfxOut.nSamplesPerSec * _wfxOut.nChannels / 8; } public void Dispose() { _evt.Close(); GC.SuppressFinalize(this); } #endregion #region Internal Methods /// <summary> /// Begin to play /// </summary> internal override void Begin(byte[] wfx) { if (_deviceOpen) { System.Diagnostics.Debug.Assert(false); throw new InvalidOperationException(); } // Get the audio format if conversion is needed _wfxIn = WAVEFORMATEX.ToWaveHeader(wfx); _doConversion = _pcmConverter.PrepareConverter(ref _wfxIn, ref _wfxOut); if (_totalByteWrittens == 0 && _hasHeader) { WriteWaveHeader(_stream, _wfxOut, _startStreamPosition, 0); } _bytesWritten = 0; // set the flags _aborted = false; _deviceOpen = true; } /// <summary> /// Begin to play /// </summary> internal override void End() { if (!_deviceOpen) { System.Diagnostics.Debug.Assert(false); throw new InvalidOperationException(); } _deviceOpen = false; if (!_aborted) { if (_hasHeader) { long position = _stream.Position; WriteWaveHeader(_stream, _wfxOut, _startStreamPosition, _totalByteWrittens); _stream.Seek(position, SeekOrigin.Begin); } } } #region AudioDevice implementation /// <summary> /// Play a wave file. /// </summary> internal override void Play(byte[] buffer) { if (!_deviceOpen) { System.Diagnostics.Debug.Assert(false); } else { byte[] abOut = _doConversion ? _pcmConverter.ConvertSamples(buffer) : buffer; if (_paused) { _evt.WaitOne(); _evt.Reset(); } if (!_aborted) { _stream.Write(abOut, 0, abOut.Length); _totalByteWrittens += abOut.Length; _bytesWritten += abOut.Length; } } } /// <summary> /// Pause the playback of a sound. /// </summary> internal override void Pause() { if (!_aborted && !_paused) { lock (_noWriteOutLock) { _paused = true; } } } /// <summary> /// Resume the playback of a paused sound. /// </summary> internal override void Resume() { if (!_aborted && _paused) { lock (_noWriteOutLock) { _paused = false; _evt.Set(); } } } /// <summary> /// Wait for all the queued buffers to be played /// </summary> internal override void Abort() { lock (_noWriteOutLock) { _aborted = true; _paused = false; _evt.Set(); } } internal override void InjectEvent(TTSEvent ttsEvent) { if (!_aborted && _asyncDispatch != null) { _asyncDispatch.Post(ttsEvent); } } /// <summary> /// File operation are basically synchronous /// </summary> internal override void WaitUntilDone() { lock (_noWriteOutLock) { } } #endregion #endregion #region Internal Fields internal override TimeSpan Duration { get { if (_wfxIn.nAvgBytesPerSec == 0) { return new TimeSpan(0); } return new TimeSpan((_bytesWritten * TimeSpan.TicksPerSecond) / _wfxIn.nAvgBytesPerSec); } } internal override long Position { get { return _stream.Position; } } internal override byte[] WaveFormat { get { return _wfxOut.ToBytes(); } } #endregion #region Private Fields protected ManualResetEvent _evt = new(false); protected bool _deviceOpen; protected Stream _stream; protected PcmConverter _pcmConverter = new(); protected bool _doConversion; protected bool _paused; protected int _totalByteWrittens; protected int _bytesWritten; #endregion #region Private Fields private IAsyncDispatch _asyncDispatch; private object _noWriteOutLock = new(); private WAVEFORMATEX _wfxIn; private WAVEFORMATEX _wfxOut; private bool _hasHeader; private long _startStreamPosition; #endregion } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/tests/JIT/HardwareIntrinsics/General/Vector64/AndNot.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AndNotByte() { var test = new VectorBinaryOpTest__AndNotByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__AndNotByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__AndNotByte testClass) { var result = Vector64.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__AndNotByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public VectorBinaryOpTest__AndNotByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.AndNot( Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.AndNot), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.AndNot), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = Vector64.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__AndNotByte(); var result = Vector64.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(left[0] & ~right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(left[i] & ~right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.AndNot)}<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 AndNotByte() { var test = new VectorBinaryOpTest__AndNotByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__AndNotByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__AndNotByte testClass) { var result = Vector64.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__AndNotByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public VectorBinaryOpTest__AndNotByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.AndNot( Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.AndNot), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.AndNot), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = Vector64.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__AndNotByte(); var result = Vector64.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(left[0] & ~right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(left[i] & ~right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.AndNot)}<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightArithmeticNarrowingSaturateUnsignedUpper.Vector128.UInt32.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1() { var test = new ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, Int64[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt32> _fld1; public Vector128<Int64> _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<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1 testClass) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1 testClass) { fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 1; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector64<UInt32> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector64<UInt32> _fld1; private Vector128<Int64> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), (byte)1 }); 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(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(pClsVar2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1(); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1(); fixed (Vector64<UInt32>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&test._fld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt32> firstOp, Vector128<Int64> secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), secondOp); 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* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int64>>()); 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[] firstOp, Int64[] secondOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(firstOp, secondOp, Imm, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper)}<UInt32>(Vector64<UInt32>, Vector128<Int64>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1() { var test = new ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, Int64[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt32> _fld1; public Vector128<Int64> _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<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1 testClass) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1 testClass) { fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 1; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector64<UInt32> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector64<UInt32> _fld1; private Vector128<Int64> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), (byte)1 }); 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(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(pClsVar2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1(); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightArithmeticNarrowingSaturateUnsignedUpper_Vector128_UInt32_1(); fixed (Vector64<UInt32>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper( AdvSimd.LoadVector64((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&test._fld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt32> firstOp, Vector128<Int64> secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), secondOp); 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* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int64>>()); 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[] firstOp, Int64[] secondOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightArithmeticNarrowingSaturateUnsignedUpper(firstOp, secondOp, Imm, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightArithmeticNarrowingSaturateUnsignedUpper)}<UInt32>(Vector64<UInt32>, Vector128<Int64>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.ValueTypedMember.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { private class ValueTypeToInterfaceConverter : JsonConverter<IMemberInterface> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override IMemberInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, IMemberInterface value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : value.Value, options); } } private class ValueTypeToObjectConverter : JsonConverter<object> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : ((IMemberInterface)value).Value, options); } } [Fact] public static void AssignmentToValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToNullableValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void AssignmentToNullableValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void ValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void ValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberWithNullsToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } [Fact] public static void NullableValueTypedMemberWithNullsToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { private class ValueTypeToInterfaceConverter : JsonConverter<IMemberInterface> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override IMemberInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, IMemberInterface value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : value.Value, options); } } private class ValueTypeToObjectConverter : JsonConverter<object> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : ((IMemberInterface)value).Value, options); } } [Fact] public static void AssignmentToValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToNullableValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void AssignmentToNullableValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void ValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void ValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberWithNullsToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } [Fact] public static void NullableValueTypedMemberWithNullsToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/tests/nativeaot/SmokeTests/UnitTests/BasicThreading.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; class BasicThreading { public const int Pass = 100; public const int Fail = -1; internal static int Run() { SimpleReadWriteThreadStaticTest.Run(42, "SimpleReadWriteThreadStatic"); ThreadStaticsTestWithTasks.Run(); if (ThreadTest.Run() != Pass) return Fail; if (TimerTest.Run() != Pass) return Fail; if (FinalizeTest.Run() != Pass) return Fail; return Pass; } } class FinalizeTest { public static bool visited = false; public class Dummy { ~Dummy() { FinalizeTest.visited = true; } } public static int Run() { int iterationCount = 0; while (!visited && iterationCount++ < 1000000) { GC.KeepAlive(new Dummy()); GC.Collect(); } if (visited) { Console.WriteLine("FinalizeTest passed"); return BasicThreading.Pass; } else { Console.WriteLine("FinalizeTest failed"); return BasicThreading.Fail; } } } class SimpleReadWriteThreadStaticTest { public static void Run(int intValue, string stringValue) { NonGenericReadWriteThreadStaticsTest(intValue, "NonGeneric" + stringValue); GenericReadWriteThreadStaticsTest(intValue + 1, "Generic" + stringValue); } class NonGenericType { [ThreadStatic] public static int IntValue; [ThreadStatic] public static string StringValue; } class GenericType<T, V> { [ThreadStatic] public static T ValueT; [ThreadStatic] public static V ValueV; } static void NonGenericReadWriteThreadStaticsTest(int intValue, string stringValue) { NonGenericType.IntValue = intValue; NonGenericType.StringValue = stringValue; if (NonGenericType.IntValue != intValue) { throw new Exception("SimpleReadWriteThreadStaticsTest: wrong integer value: " + NonGenericType.IntValue.ToString()); } if (NonGenericType.StringValue != stringValue) { throw new Exception("SimpleReadWriteThreadStaticsTest: wrong string value: " + NonGenericType.StringValue); } } static void GenericReadWriteThreadStaticsTest(int intValue, string stringValue) { GenericType<int, string>.ValueT = intValue; GenericType<int, string>.ValueV = stringValue; if (GenericType<int, string>.ValueT != intValue) { throw new Exception("GenericReadWriteThreadStaticsTest1a: wrong integer value: " + GenericType<int, string>.ValueT.ToString()); } if (GenericType<int, string>.ValueV != stringValue) { throw new Exception("GenericReadWriteThreadStaticsTest1b: wrong string value: " + GenericType<int, string>.ValueV); } intValue++; GenericType<int, int>.ValueT = intValue; GenericType<int, int>.ValueV = intValue + 1; if (GenericType<int, int>.ValueT != intValue) { throw new Exception("GenericReadWriteThreadStaticsTest2a: wrong integer value: " + GenericType<int, string>.ValueT.ToString()); } if (GenericType<int, int>.ValueV != (intValue + 1)) { throw new Exception("GenericReadWriteThreadStaticsTest2b: wrong integer value: " + GenericType<int, string>.ValueV.ToString()); } GenericType<string, string>.ValueT = stringValue + "a"; GenericType<string, string>.ValueV = stringValue + "b"; if (GenericType<string, string>.ValueT != (stringValue + "a")) { throw new Exception("GenericReadWriteThreadStaticsTest3a: wrong string value: " + GenericType<string, string>.ValueT); } if (GenericType<string, string>.ValueV != (stringValue + "b")) { throw new Exception("GenericReadWriteThreadStaticsTest3b: wrong string value: " + GenericType<string, string>.ValueV); } } } class ThreadStaticsTestWithTasks { static object lockObject = new object(); const int TotalTaskCount = 32; public static void Run() { Task[] tasks = new Task[TotalTaskCount]; for (int i = 0; i < tasks.Length; ++i) { tasks[i] = Task.Factory.StartNew((param) => { int index = (int)param; int intTestValue = index * 10; string stringTestValue = "ThreadStaticsTestWithTasks" + index; // Try to run the on every other task if ((index % 2) == 0) { lock (lockObject) { SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue); } } else { SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue); } }, i); } for (int i = 0; i < tasks.Length; ++i) { tasks[i].Wait(); } } } class ThreadTest { private static readonly List<Thread> s_startedThreads = new List<Thread>(); private static int s_passed; private static int s_failed; private static void Expect(bool condition, string message) { if (condition) { Interlocked.Increment(ref s_passed); } else { Interlocked.Increment(ref s_failed); Console.WriteLine("ERROR: " + message); } } private static void ExpectException<T>(Action action, string message) { Exception ex = null; try { action(); } catch (Exception e) { ex = e; } if (!(ex is T)) { message += string.Format(" (caught {0})", (ex == null) ? "no exception" : ex.GetType().Name); } Expect(ex is T, message); } private static void ExpectPassed(string testName, int expectedPassed) { // Wait for all started threads to finish execution foreach (Thread t in s_startedThreads) { t.Join(); } s_startedThreads.Clear(); Expect(s_passed == expectedPassed, string.Format("{0}: Expected s_passed == {1}, got {2}", testName, expectedPassed, s_passed)); s_passed = 0; } private static void TestStartMethod() { // Case 1: new Thread(ThreadStart).Start() var t1 = new Thread(() => Expect(true, "Expected t1 to start")); t1.Start(); s_startedThreads.Add(t1); // Case 2: new Thread(ThreadStart).Start(parameter) var t2 = new Thread(() => Expect(false, "This thread must not be started")); // InvalidOperationException: The thread was created with a ThreadStart delegate that does not accept a parameter. ExpectException<InvalidOperationException>(() => t2.Start(null), "Expected InvalidOperationException for t2.Start()"); // Case 3: new Thread(ParameterizedThreadStart).Start() var t3 = new Thread(obj => Expect(obj == null, "Expected obj == null")); t3.Start(); s_startedThreads.Add(t3); // Case 4: new Thread(ParameterizedThreadStart).Start(parameter) var t4 = new Thread(obj => Expect((int)obj == 42, "Expected (int)obj == 42")); t4.Start(42); s_startedThreads.Add(t4); // Start an unstarted resurrected thread. // CoreCLR: ThreadStateException, CoreRT: no exception. Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); unstartedResurrected.Start(); s_startedThreads.Add(unstartedResurrected); // Threads cannot started more than once t1.Join(); ExpectException<ThreadStateException>(() => t1.Start(), "Expected ThreadStateException for t1.Start()"); ExpectException<ThreadStateException>(() => Thread.CurrentThread.Start(), "Expected ThreadStateException for CurrentThread.Start()"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); ExpectException<ThreadStateException>(() => stoppedResurrected.Start(), "Expected ThreadStateException for stoppedResurrected.Start()"); ExpectPassed(nameof(TestStartMethod), 7); } private static void TestJoinMethod() { var t = new Thread(() => { }); ExpectException<InvalidOperationException>(() => t.Start(null), "Expected InvalidOperationException for t.Start()"); ExpectException<ThreadStateException>(() => t.Join(), "Expected ThreadStateException for t.Join()"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.Join(1), "Expected stoppedResurrected.Join(1) to return true"); Expect(!Thread.CurrentThread.Join(1), "Expected CurrentThread.Join(1) to return false"); ExpectPassed(nameof(TestJoinMethod), 4); } private static void TestCurrentThreadProperty() { Thread t = null; t = new Thread(() => Expect(Thread.CurrentThread == t, "Expected CurrentThread == t on thread t")); t.Start(); s_startedThreads.Add(t); Expect(Thread.CurrentThread != t, "Expected CurrentThread != t on main thread"); ExpectPassed(nameof(TestCurrentThreadProperty), 2); } private static void TestNameProperty() { var t = new Thread(() => { }); t.Name = null; // It is OK to set the null Name multiple times t.Name = null; Expect(t.Name == null, "Expected t.Name == null"); const string ThreadName = "My thread"; t.Name = ThreadName; Expect(t.Name == ThreadName, string.Format("Expected t.Name == \"{0}\"", ThreadName)); t.Name = null; Expect(t.Name == null, "Expected t.Name == null"); ExpectPassed(nameof(TestNameProperty), 3); } private static void TestConcurrentIsBackgroundProperty() { int spawnedCount = 10000; Task[] spawned = new Task[spawnedCount]; for (int i = 0; i < spawnedCount; i++) { ManualResetEventSlim mres = new ManualResetEventSlim(false); var t = new Thread(() => { Thread.CurrentThread.IsBackground = !Thread.CurrentThread.IsBackground; mres.Wait(); }); s_startedThreads.Add(t); spawned[i] = Task.Factory.StartNew(() => { t.Start(); }); Task.Factory.StartNew(() => { Expect(true, "Always true"); for (int i = 0; i < 10000; i++) { t.IsBackground = i % 2 == 0; } mres.Set(); }); } Task.WaitAll(spawned); ExpectPassed(nameof(TestConcurrentIsBackgroundProperty), spawnedCount); } private static void TestIsBackgroundProperty() { // Thread created using Thread.Start var t_event = new AutoResetEvent(false); var t = new Thread(() => t_event.WaitOne()); t.Start(); s_startedThreads.Add(t); Expect(!t.IsBackground, "Expected t.IsBackground == false"); t_event.Set(); t.Join(); ExpectException<ThreadStateException>(() => Console.WriteLine(t.IsBackground), "Expected ThreadStateException for t.IsBackground"); // Thread pool thread Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsBackground, "Expected IsBackground == true")).Wait(); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.IsBackground == false, "Expected unstartedResurrected.IsBackground == false"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); ExpectException<ThreadStateException>(() => Console.WriteLine(stoppedResurrected.IsBackground), "Expected ThreadStateException for stoppedResurrected.IsBackground"); // Main thread Expect(!Thread.CurrentThread.IsBackground, "Expected CurrentThread.IsBackground == false"); ExpectPassed(nameof(TestIsBackgroundProperty), 6); } private static void TestIsThreadPoolThreadProperty() { #if false // The IsThreadPoolThread property is not in the contract version we compile against at present var t = new Thread(() => { }); Expect(!t.IsThreadPoolThread, "Expected t.IsThreadPoolThread == false"); Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsThreadPoolThread, "Expected IsThreadPoolThread == true")).Wait(); Expect(!Thread.CurrentThread.IsThreadPoolThread, "Expected CurrentThread.IsThreadPoolThread == false"); ExpectPassed(nameof(TestIsThreadPoolThreadProperty), 3); #endif } private static void TestManagedThreadIdProperty() { int t_id = 0; var t = new Thread(() => { Expect(Thread.CurrentThread.ManagedThreadId == t_id, "Expected CurrentTread.ManagedThreadId == t_id on thread t"); Expect(Environment.CurrentManagedThreadId == t_id, "Expected Environment.CurrentManagedThreadId == t_id on thread t"); }); t_id = t.ManagedThreadId; Expect(t_id != 0, "Expected t_id != 0"); Expect(Thread.CurrentThread.ManagedThreadId != t_id, "Expected CurrentTread.ManagedThreadId != t_id on main thread"); Expect(Environment.CurrentManagedThreadId != t_id, "Expected Environment.CurrentManagedThreadId != t_id on main thread"); t.Start(); s_startedThreads.Add(t); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.ManagedThreadId != 0, "Expected unstartedResurrected.ManagedThreadId != 0"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.ManagedThreadId != 0, "Expected stoppedResurrected.ManagedThreadId != 0"); ExpectPassed(nameof(TestManagedThreadIdProperty), 7); } private static void TestThreadStateProperty() { var t_event = new AutoResetEvent(false); var t = new Thread(() => t_event.WaitOne()); Expect(t.ThreadState == ThreadState.Unstarted, "Expected t.ThreadState == ThreadState.Unstarted"); t.Start(); s_startedThreads.Add(t); Expect(t.ThreadState == ThreadState.Running || t.ThreadState == ThreadState.WaitSleepJoin, "Expected t.ThreadState is either ThreadState.Running or ThreadState.WaitSleepJoin"); t_event.Set(); t.Join(); Expect(t.ThreadState == ThreadState.Stopped, "Expected t.ThreadState == ThreadState.Stopped"); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.ThreadState == ThreadState.Unstarted, "Expected unstartedResurrected.ThreadState == ThreadState.Unstarted"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.ThreadState == ThreadState.Stopped, "Expected stoppedResurrected.ThreadState == ThreadState.Stopped"); ExpectPassed(nameof(TestThreadStateProperty), 5); } private static unsafe void DoStackAlloc(int size) { byte* buffer = stackalloc byte[size]; Volatile.Write(ref buffer[0], 0); } private static void TestMaxStackSize() { #if false // The constructors with maxStackSize are not in the contract version we compile against at present // Allocate a 3 MiB buffer on the 4 MiB stack var t = new Thread(() => DoStackAlloc(3 << 20), 4 << 20); t.Start(); s_startedThreads.Add(t); #endif ExpectPassed(nameof(TestMaxStackSize), 0); } static int s_startedThreadCount = 0; private static void TestStartShutdown() { Thread[] threads = new Thread[2048]; // Creating a large number of threads for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(() => { Interlocked.Increment(ref s_startedThreadCount); }); threads[i].Start(); } // Wait for all threads to shutdown; for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } Expect(s_startedThreadCount == threads.Length, String.Format("Not all threads completed. Expected: {0}, Actual: {1}", threads.Length, s_startedThreadCount)); ExpectPassed(nameof(TestStartShutdown), 1); } public static int Run() { TestStartMethod(); TestJoinMethod(); TestCurrentThreadProperty(); TestNameProperty(); TestIsBackgroundProperty(); TestIsThreadPoolThreadProperty(); TestManagedThreadIdProperty(); TestThreadStateProperty(); TestMaxStackSize(); TestStartShutdown(); TestConcurrentIsBackgroundProperty(); return (s_failed == 0) ? BasicThreading.Pass : BasicThreading.Fail; } /// <summary> /// Creates resurrected Thread objects. /// </summary> class Resurrector { static Thread s_unstartedResurrected; static Thread s_stoppedResurrected; bool _unstarted; Thread _thread = new Thread(() => { }); Resurrector(bool unstarted) { _unstarted = unstarted; if (!unstarted) { _thread.Start(); _thread.Join(); } } ~Resurrector() { if (_unstarted && (s_unstartedResurrected == null)) { s_unstartedResurrected = _thread; } else if(!_unstarted && (s_stoppedResurrected == null)) { s_stoppedResurrected = _thread; } } [MethodImpl(MethodImplOptions.NoInlining)] static void CreateInstance(bool unstarted) { GC.KeepAlive(new Resurrector(unstarted)); } static Thread CreateResurrectedThread(ref Thread trap, bool unstarted) { trap = null; while (trap == null) { // Call twice to override the address of the first allocation on the stack (for conservative GC) CreateInstance(unstarted); CreateInstance(unstarted); GC.Collect(); GC.WaitForPendingFinalizers(); } // We would like to get a Thread object with its internal SafeHandle member disposed. // The current implementation of SafeHandle postpones disposing until the next garbage // collection. For this reason we do a couple more collections. for (int i = 0; i < 2; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } return trap; } public static Thread CreateUnstartedResurrected() { return CreateResurrectedThread(ref s_unstartedResurrected, unstarted: true); } public static Thread CreateStoppedResurrected() { return CreateResurrectedThread(ref s_stoppedResurrected, unstarted: false); } } } class TimerTest { private static AutoResetEvent s_event; private static Timer s_timer; private static volatile int s_periodicTimerCount; public static int Run() { s_event = new AutoResetEvent(false); s_timer = new Timer(TimerCallback, null, 200, Timeout.Infinite); bool timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: timer has not fired."); return BasicThreading.Fail; } // Change the timer to a very long value s_event.Reset(); s_timer.Change(3000000, Timeout.Infinite); timerFired = s_event.WaitOne(500); if (timerFired) { Console.WriteLine("The timer test failed: timer fired earlier than expected."); return BasicThreading.Fail; } // Try change existing timer to a small value and make sure it fires s_event.Reset(); s_timer.Change(200, Timeout.Infinite); timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: failed to change the existing timer."); return BasicThreading.Fail; } // Test a periodic timer s_periodicTimerCount = 0; s_event.Reset(); s_timer = new Timer(PeriodicTimerCallback, null, 200, 20); while (s_periodicTimerCount < 3) { timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: the periodic timer has not fired."); return BasicThreading.Fail; } } // Stop the periodic timer s_timer.Change(Timeout.Infinite, Timeout.Infinite); return BasicThreading.Pass; } private static void TimerCallback(object state) { s_event.Set(); } private static void PeriodicTimerCallback(object state) { Interlocked.Increment(ref s_periodicTimerCount); s_event.Set(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; class BasicThreading { public const int Pass = 100; public const int Fail = -1; internal static int Run() { SimpleReadWriteThreadStaticTest.Run(42, "SimpleReadWriteThreadStatic"); ThreadStaticsTestWithTasks.Run(); if (ThreadTest.Run() != Pass) return Fail; if (TimerTest.Run() != Pass) return Fail; if (FinalizeTest.Run() != Pass) return Fail; return Pass; } } class FinalizeTest { public static bool visited = false; public class Dummy { ~Dummy() { FinalizeTest.visited = true; } } public static int Run() { int iterationCount = 0; while (!visited && iterationCount++ < 1000000) { GC.KeepAlive(new Dummy()); GC.Collect(); } if (visited) { Console.WriteLine("FinalizeTest passed"); return BasicThreading.Pass; } else { Console.WriteLine("FinalizeTest failed"); return BasicThreading.Fail; } } } class SimpleReadWriteThreadStaticTest { public static void Run(int intValue, string stringValue) { NonGenericReadWriteThreadStaticsTest(intValue, "NonGeneric" + stringValue); GenericReadWriteThreadStaticsTest(intValue + 1, "Generic" + stringValue); } class NonGenericType { [ThreadStatic] public static int IntValue; [ThreadStatic] public static string StringValue; } class GenericType<T, V> { [ThreadStatic] public static T ValueT; [ThreadStatic] public static V ValueV; } static void NonGenericReadWriteThreadStaticsTest(int intValue, string stringValue) { NonGenericType.IntValue = intValue; NonGenericType.StringValue = stringValue; if (NonGenericType.IntValue != intValue) { throw new Exception("SimpleReadWriteThreadStaticsTest: wrong integer value: " + NonGenericType.IntValue.ToString()); } if (NonGenericType.StringValue != stringValue) { throw new Exception("SimpleReadWriteThreadStaticsTest: wrong string value: " + NonGenericType.StringValue); } } static void GenericReadWriteThreadStaticsTest(int intValue, string stringValue) { GenericType<int, string>.ValueT = intValue; GenericType<int, string>.ValueV = stringValue; if (GenericType<int, string>.ValueT != intValue) { throw new Exception("GenericReadWriteThreadStaticsTest1a: wrong integer value: " + GenericType<int, string>.ValueT.ToString()); } if (GenericType<int, string>.ValueV != stringValue) { throw new Exception("GenericReadWriteThreadStaticsTest1b: wrong string value: " + GenericType<int, string>.ValueV); } intValue++; GenericType<int, int>.ValueT = intValue; GenericType<int, int>.ValueV = intValue + 1; if (GenericType<int, int>.ValueT != intValue) { throw new Exception("GenericReadWriteThreadStaticsTest2a: wrong integer value: " + GenericType<int, string>.ValueT.ToString()); } if (GenericType<int, int>.ValueV != (intValue + 1)) { throw new Exception("GenericReadWriteThreadStaticsTest2b: wrong integer value: " + GenericType<int, string>.ValueV.ToString()); } GenericType<string, string>.ValueT = stringValue + "a"; GenericType<string, string>.ValueV = stringValue + "b"; if (GenericType<string, string>.ValueT != (stringValue + "a")) { throw new Exception("GenericReadWriteThreadStaticsTest3a: wrong string value: " + GenericType<string, string>.ValueT); } if (GenericType<string, string>.ValueV != (stringValue + "b")) { throw new Exception("GenericReadWriteThreadStaticsTest3b: wrong string value: " + GenericType<string, string>.ValueV); } } } class ThreadStaticsTestWithTasks { static object lockObject = new object(); const int TotalTaskCount = 32; public static void Run() { Task[] tasks = new Task[TotalTaskCount]; for (int i = 0; i < tasks.Length; ++i) { tasks[i] = Task.Factory.StartNew((param) => { int index = (int)param; int intTestValue = index * 10; string stringTestValue = "ThreadStaticsTestWithTasks" + index; // Try to run the on every other task if ((index % 2) == 0) { lock (lockObject) { SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue); } } else { SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue); } }, i); } for (int i = 0; i < tasks.Length; ++i) { tasks[i].Wait(); } } } class ThreadTest { private static readonly List<Thread> s_startedThreads = new List<Thread>(); private static int s_passed; private static int s_failed; private static void Expect(bool condition, string message) { if (condition) { Interlocked.Increment(ref s_passed); } else { Interlocked.Increment(ref s_failed); Console.WriteLine("ERROR: " + message); } } private static void ExpectException<T>(Action action, string message) { Exception ex = null; try { action(); } catch (Exception e) { ex = e; } if (!(ex is T)) { message += string.Format(" (caught {0})", (ex == null) ? "no exception" : ex.GetType().Name); } Expect(ex is T, message); } private static void ExpectPassed(string testName, int expectedPassed) { // Wait for all started threads to finish execution foreach (Thread t in s_startedThreads) { t.Join(); } s_startedThreads.Clear(); Expect(s_passed == expectedPassed, string.Format("{0}: Expected s_passed == {1}, got {2}", testName, expectedPassed, s_passed)); s_passed = 0; } private static void TestStartMethod() { // Case 1: new Thread(ThreadStart).Start() var t1 = new Thread(() => Expect(true, "Expected t1 to start")); t1.Start(); s_startedThreads.Add(t1); // Case 2: new Thread(ThreadStart).Start(parameter) var t2 = new Thread(() => Expect(false, "This thread must not be started")); // InvalidOperationException: The thread was created with a ThreadStart delegate that does not accept a parameter. ExpectException<InvalidOperationException>(() => t2.Start(null), "Expected InvalidOperationException for t2.Start()"); // Case 3: new Thread(ParameterizedThreadStart).Start() var t3 = new Thread(obj => Expect(obj == null, "Expected obj == null")); t3.Start(); s_startedThreads.Add(t3); // Case 4: new Thread(ParameterizedThreadStart).Start(parameter) var t4 = new Thread(obj => Expect((int)obj == 42, "Expected (int)obj == 42")); t4.Start(42); s_startedThreads.Add(t4); // Start an unstarted resurrected thread. // CoreCLR: ThreadStateException, CoreRT: no exception. Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); unstartedResurrected.Start(); s_startedThreads.Add(unstartedResurrected); // Threads cannot started more than once t1.Join(); ExpectException<ThreadStateException>(() => t1.Start(), "Expected ThreadStateException for t1.Start()"); ExpectException<ThreadStateException>(() => Thread.CurrentThread.Start(), "Expected ThreadStateException for CurrentThread.Start()"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); ExpectException<ThreadStateException>(() => stoppedResurrected.Start(), "Expected ThreadStateException for stoppedResurrected.Start()"); ExpectPassed(nameof(TestStartMethod), 7); } private static void TestJoinMethod() { var t = new Thread(() => { }); ExpectException<InvalidOperationException>(() => t.Start(null), "Expected InvalidOperationException for t.Start()"); ExpectException<ThreadStateException>(() => t.Join(), "Expected ThreadStateException for t.Join()"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.Join(1), "Expected stoppedResurrected.Join(1) to return true"); Expect(!Thread.CurrentThread.Join(1), "Expected CurrentThread.Join(1) to return false"); ExpectPassed(nameof(TestJoinMethod), 4); } private static void TestCurrentThreadProperty() { Thread t = null; t = new Thread(() => Expect(Thread.CurrentThread == t, "Expected CurrentThread == t on thread t")); t.Start(); s_startedThreads.Add(t); Expect(Thread.CurrentThread != t, "Expected CurrentThread != t on main thread"); ExpectPassed(nameof(TestCurrentThreadProperty), 2); } private static void TestNameProperty() { var t = new Thread(() => { }); t.Name = null; // It is OK to set the null Name multiple times t.Name = null; Expect(t.Name == null, "Expected t.Name == null"); const string ThreadName = "My thread"; t.Name = ThreadName; Expect(t.Name == ThreadName, string.Format("Expected t.Name == \"{0}\"", ThreadName)); t.Name = null; Expect(t.Name == null, "Expected t.Name == null"); ExpectPassed(nameof(TestNameProperty), 3); } private static void TestConcurrentIsBackgroundProperty() { int spawnedCount = 10000; Task[] spawned = new Task[spawnedCount]; for (int i = 0; i < spawnedCount; i++) { ManualResetEventSlim mres = new ManualResetEventSlim(false); var t = new Thread(() => { Thread.CurrentThread.IsBackground = !Thread.CurrentThread.IsBackground; mres.Wait(); }); s_startedThreads.Add(t); spawned[i] = Task.Factory.StartNew(() => { t.Start(); }); Task.Factory.StartNew(() => { Expect(true, "Always true"); for (int i = 0; i < 10000; i++) { t.IsBackground = i % 2 == 0; } mres.Set(); }); } Task.WaitAll(spawned); ExpectPassed(nameof(TestConcurrentIsBackgroundProperty), spawnedCount); } private static void TestIsBackgroundProperty() { // Thread created using Thread.Start var t_event = new AutoResetEvent(false); var t = new Thread(() => t_event.WaitOne()); t.Start(); s_startedThreads.Add(t); Expect(!t.IsBackground, "Expected t.IsBackground == false"); t_event.Set(); t.Join(); ExpectException<ThreadStateException>(() => Console.WriteLine(t.IsBackground), "Expected ThreadStateException for t.IsBackground"); // Thread pool thread Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsBackground, "Expected IsBackground == true")).Wait(); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.IsBackground == false, "Expected unstartedResurrected.IsBackground == false"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); ExpectException<ThreadStateException>(() => Console.WriteLine(stoppedResurrected.IsBackground), "Expected ThreadStateException for stoppedResurrected.IsBackground"); // Main thread Expect(!Thread.CurrentThread.IsBackground, "Expected CurrentThread.IsBackground == false"); ExpectPassed(nameof(TestIsBackgroundProperty), 6); } private static void TestIsThreadPoolThreadProperty() { #if false // The IsThreadPoolThread property is not in the contract version we compile against at present var t = new Thread(() => { }); Expect(!t.IsThreadPoolThread, "Expected t.IsThreadPoolThread == false"); Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsThreadPoolThread, "Expected IsThreadPoolThread == true")).Wait(); Expect(!Thread.CurrentThread.IsThreadPoolThread, "Expected CurrentThread.IsThreadPoolThread == false"); ExpectPassed(nameof(TestIsThreadPoolThreadProperty), 3); #endif } private static void TestManagedThreadIdProperty() { int t_id = 0; var t = new Thread(() => { Expect(Thread.CurrentThread.ManagedThreadId == t_id, "Expected CurrentTread.ManagedThreadId == t_id on thread t"); Expect(Environment.CurrentManagedThreadId == t_id, "Expected Environment.CurrentManagedThreadId == t_id on thread t"); }); t_id = t.ManagedThreadId; Expect(t_id != 0, "Expected t_id != 0"); Expect(Thread.CurrentThread.ManagedThreadId != t_id, "Expected CurrentTread.ManagedThreadId != t_id on main thread"); Expect(Environment.CurrentManagedThreadId != t_id, "Expected Environment.CurrentManagedThreadId != t_id on main thread"); t.Start(); s_startedThreads.Add(t); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.ManagedThreadId != 0, "Expected unstartedResurrected.ManagedThreadId != 0"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.ManagedThreadId != 0, "Expected stoppedResurrected.ManagedThreadId != 0"); ExpectPassed(nameof(TestManagedThreadIdProperty), 7); } private static void TestThreadStateProperty() { var t_event = new AutoResetEvent(false); var t = new Thread(() => t_event.WaitOne()); Expect(t.ThreadState == ThreadState.Unstarted, "Expected t.ThreadState == ThreadState.Unstarted"); t.Start(); s_startedThreads.Add(t); Expect(t.ThreadState == ThreadState.Running || t.ThreadState == ThreadState.WaitSleepJoin, "Expected t.ThreadState is either ThreadState.Running or ThreadState.WaitSleepJoin"); t_event.Set(); t.Join(); Expect(t.ThreadState == ThreadState.Stopped, "Expected t.ThreadState == ThreadState.Stopped"); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.ThreadState == ThreadState.Unstarted, "Expected unstartedResurrected.ThreadState == ThreadState.Unstarted"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.ThreadState == ThreadState.Stopped, "Expected stoppedResurrected.ThreadState == ThreadState.Stopped"); ExpectPassed(nameof(TestThreadStateProperty), 5); } private static unsafe void DoStackAlloc(int size) { byte* buffer = stackalloc byte[size]; Volatile.Write(ref buffer[0], 0); } private static void TestMaxStackSize() { #if false // The constructors with maxStackSize are not in the contract version we compile against at present // Allocate a 3 MiB buffer on the 4 MiB stack var t = new Thread(() => DoStackAlloc(3 << 20), 4 << 20); t.Start(); s_startedThreads.Add(t); #endif ExpectPassed(nameof(TestMaxStackSize), 0); } static int s_startedThreadCount = 0; private static void TestStartShutdown() { Thread[] threads = new Thread[2048]; // Creating a large number of threads for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(() => { Interlocked.Increment(ref s_startedThreadCount); }); threads[i].Start(); } // Wait for all threads to shutdown; for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } Expect(s_startedThreadCount == threads.Length, String.Format("Not all threads completed. Expected: {0}, Actual: {1}", threads.Length, s_startedThreadCount)); ExpectPassed(nameof(TestStartShutdown), 1); } public static int Run() { TestStartMethod(); TestJoinMethod(); TestCurrentThreadProperty(); TestNameProperty(); TestIsBackgroundProperty(); TestIsThreadPoolThreadProperty(); TestManagedThreadIdProperty(); TestThreadStateProperty(); TestMaxStackSize(); TestStartShutdown(); TestConcurrentIsBackgroundProperty(); return (s_failed == 0) ? BasicThreading.Pass : BasicThreading.Fail; } /// <summary> /// Creates resurrected Thread objects. /// </summary> class Resurrector { static Thread s_unstartedResurrected; static Thread s_stoppedResurrected; bool _unstarted; Thread _thread = new Thread(() => { }); Resurrector(bool unstarted) { _unstarted = unstarted; if (!unstarted) { _thread.Start(); _thread.Join(); } } ~Resurrector() { if (_unstarted && (s_unstartedResurrected == null)) { s_unstartedResurrected = _thread; } else if(!_unstarted && (s_stoppedResurrected == null)) { s_stoppedResurrected = _thread; } } [MethodImpl(MethodImplOptions.NoInlining)] static void CreateInstance(bool unstarted) { GC.KeepAlive(new Resurrector(unstarted)); } static Thread CreateResurrectedThread(ref Thread trap, bool unstarted) { trap = null; while (trap == null) { // Call twice to override the address of the first allocation on the stack (for conservative GC) CreateInstance(unstarted); CreateInstance(unstarted); GC.Collect(); GC.WaitForPendingFinalizers(); } // We would like to get a Thread object with its internal SafeHandle member disposed. // The current implementation of SafeHandle postpones disposing until the next garbage // collection. For this reason we do a couple more collections. for (int i = 0; i < 2; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } return trap; } public static Thread CreateUnstartedResurrected() { return CreateResurrectedThread(ref s_unstartedResurrected, unstarted: true); } public static Thread CreateStoppedResurrected() { return CreateResurrectedThread(ref s_stoppedResurrected, unstarted: false); } } } class TimerTest { private static AutoResetEvent s_event; private static Timer s_timer; private static volatile int s_periodicTimerCount; public static int Run() { s_event = new AutoResetEvent(false); s_timer = new Timer(TimerCallback, null, 200, Timeout.Infinite); bool timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: timer has not fired."); return BasicThreading.Fail; } // Change the timer to a very long value s_event.Reset(); s_timer.Change(3000000, Timeout.Infinite); timerFired = s_event.WaitOne(500); if (timerFired) { Console.WriteLine("The timer test failed: timer fired earlier than expected."); return BasicThreading.Fail; } // Try change existing timer to a small value and make sure it fires s_event.Reset(); s_timer.Change(200, Timeout.Infinite); timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: failed to change the existing timer."); return BasicThreading.Fail; } // Test a periodic timer s_periodicTimerCount = 0; s_event.Reset(); s_timer = new Timer(PeriodicTimerCallback, null, 200, 20); while (s_periodicTimerCount < 3) { timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: the periodic timer has not fired."); return BasicThreading.Fail; } } // Stop the periodic timer s_timer.Change(Timeout.Infinite, Timeout.Infinite); return BasicThreading.Pass; } private static void TimerCallback(object state) { s_event.Set(); } private static void PeriodicTimerCallback(object state) { Interlocked.Increment(ref s_periodicTimerCount); s_event.Set(); } }
-1
dotnet/runtime
66,216
Add missing regex position check after BOL optimization
Fixes https://github.com/dotnet/runtime/issues/66212
stephentoub
2022-03-04T20:44:31Z
2022-03-07T00:13:14Z
9f513350e3cea5cc56f9d7fb8e006382ec5043ff
277e12ba998ff91c49ef96c378b616369d7e9af7
Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using Internal.Text; using Internal.TypeSystem; using Internal.NativeFormat; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Hashtable of all exact (non-canonical) generic method instantiations compiled in the module. /// </summary> public sealed class ExactMethodInstantiationsNode : ObjectNode, ISymbolDefinitionNode { private ObjectAndOffsetSymbolNode _endSymbol; private ExternalReferencesTableNode _externalReferences; public ExactMethodInstantiationsNode(ExternalReferencesTableNode externalReferences) { _endSymbol = new ObjectAndOffsetSymbolNode(this, 0, "__exact_method_instantiations_End", true); _externalReferences = externalReferences; } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix).Append("__exact_method_instantiations"); } public ISymbolDefinitionNode EndSymbol => _endSymbol; public int Offset => 0; public override bool IsShareable => false; public override ObjectNodeSection Section => _externalReferences.Section; public override bool StaticDependenciesAreComputed => true; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { // Dependencies for this node are tracked by the method code nodes if (relocsOnly) return new ObjectData(Array.Empty<byte>(), Array.Empty<Relocation>(), 1, new ISymbolDefinitionNode[] { this }); // Ensure the native layout data has been saved, in order to get valid Vertex offsets for the signature Vertices factory.MetadataManager.NativeLayoutInfo.SaveNativeLayoutInfoWriter(factory); NativeWriter nativeWriter = new NativeWriter(); VertexHashtable hashtable = new VertexHashtable(); Section nativeSection = nativeWriter.NewSection(); nativeSection.Place(hashtable); foreach (MethodDesc method in factory.MetadataManager.GetCompiledMethods()) { if (!IsMethodEligibleForTracking(factory, method)) continue; // Get the method pointer vertex bool getUnboxingStub = method.OwningType.IsValueType && !method.Signature.IsStatic; IMethodNode methodEntryPointNode = factory.MethodEntrypoint(method, getUnboxingStub); Vertex methodPointer = nativeWriter.GetUnsignedConstant(_externalReferences.GetIndex(methodEntryPointNode)); // Get native layout vertices for the declaring type ISymbolNode declaringTypeNode = factory.NecessaryTypeSymbol(method.OwningType); Vertex declaringType = nativeWriter.GetUnsignedConstant(_externalReferences.GetIndex(declaringTypeNode)); // Get a vertex sequence for the method instantiation args if any VertexSequence arguments = new VertexSequence(); foreach (var arg in method.Instantiation) { ISymbolNode argNode = factory.NecessaryTypeSymbol(arg); arguments.Append(nativeWriter.GetUnsignedConstant(_externalReferences.GetIndex(argNode))); } // Get the name and sig of the method. // Note: the method name and signature are stored in the NativeLayoutInfo blob, not in the hashtable we build here. NativeLayoutMethodNameAndSignatureVertexNode nameAndSig = factory.NativeLayout.MethodNameAndSignatureVertex(method.GetTypicalMethodDefinition()); NativeLayoutPlacedSignatureVertexNode placedNameAndSig = factory.NativeLayout.PlacedSignatureVertex(nameAndSig); Debug.Assert(placedNameAndSig.SavedVertex != null); Vertex placedNameAndSigOffsetSig = nativeWriter.GetOffsetSignature(placedNameAndSig.SavedVertex); // Get the vertex for the completed method signature Vertex methodSignature = nativeWriter.GetTuple(declaringType, placedNameAndSigOffsetSig, arguments); // Make the generic method entry vertex Vertex entry = nativeWriter.GetTuple(methodSignature, methodPointer); // Add to the hash table, hashed by the containing type's hashcode uint hashCode = (uint)method.OwningType.GetHashCode(); hashtable.Append(hashCode, nativeSection.Place(entry)); } byte[] streamBytes = nativeWriter.Save(); _endSymbol.SetSymbolOffset(streamBytes.Length); return new ObjectData(streamBytes, Array.Empty<Relocation>(), 1, new ISymbolDefinitionNode[] { this, _endSymbol }); } public static void GetExactMethodInstantiationDependenciesForMethod(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) { if (!IsMethodEligibleForTracking(factory, method)) return; dependencies = dependencies ?? new DependencyList(); // Method entry point dependency bool getUnboxingStub = method.OwningType.IsValueType && !method.Signature.IsStatic; IMethodNode methodEntryPointNode = factory.MethodEntrypoint(method, getUnboxingStub); dependencies.Add(new DependencyListEntry(methodEntryPointNode, "Exact method instantiation entry")); // Get native layout dependencies for the declaring type dependencies.Add(new DependencyListEntry(factory.NecessaryTypeSymbol(method.OwningType), "Exact method instantiation entry")); // Get native layout dependencies for the method instantiation args foreach (var arg in method.Instantiation) dependencies.Add(new DependencyListEntry(factory.NecessaryTypeSymbol(arg), "Exact method instantiation entry")); // Get native layout dependencies for the method signature. NativeLayoutMethodNameAndSignatureVertexNode nameAndSig = factory.NativeLayout.MethodNameAndSignatureVertex(method.GetTypicalMethodDefinition()); dependencies.Add(new DependencyListEntry(factory.NativeLayout.PlacedSignatureVertex(nameAndSig), "Exact method instantiation entry")); } private static bool IsMethodEligibleForTracking(NodeFactory factory, MethodDesc method) { // Runtime determined methods should never show up here. Debug.Assert(!method.IsRuntimeDeterminedExactMethod); if (method.IsAbstract) return false; if (!method.HasInstantiation) return false; // This hashtable is only for method instantiations that don't use generic dictionaries, // so check if the given method is shared before proceeding if (method.IsSharedByGenericInstantiations || method.GetCanonMethodTarget(CanonicalFormKind.Specific) != method) return false; // The hashtable is used to find implementations of generic virtual methods at runtime if (method.IsVirtual) return true; // The hashtable is also used for reflection if (!factory.MetadataManager.IsReflectionBlocked(method)) return true; // The rest of the entries are potentially only useful for the universal // canonical type loader. return factory.TypeSystemContext.SupportsUniversalCanon; } protected internal override int Phase => (int)ObjectNodePhase.Ordered; public override int ClassCode => (int)ObjectNodeOrder.ExactMethodInstantiationsNode; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using Internal.Text; using Internal.TypeSystem; using Internal.NativeFormat; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Hashtable of all exact (non-canonical) generic method instantiations compiled in the module. /// </summary> public sealed class ExactMethodInstantiationsNode : ObjectNode, ISymbolDefinitionNode { private ObjectAndOffsetSymbolNode _endSymbol; private ExternalReferencesTableNode _externalReferences; public ExactMethodInstantiationsNode(ExternalReferencesTableNode externalReferences) { _endSymbol = new ObjectAndOffsetSymbolNode(this, 0, "__exact_method_instantiations_End", true); _externalReferences = externalReferences; } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix).Append("__exact_method_instantiations"); } public ISymbolDefinitionNode EndSymbol => _endSymbol; public int Offset => 0; public override bool IsShareable => false; public override ObjectNodeSection Section => _externalReferences.Section; public override bool StaticDependenciesAreComputed => true; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { // Dependencies for this node are tracked by the method code nodes if (relocsOnly) return new ObjectData(Array.Empty<byte>(), Array.Empty<Relocation>(), 1, new ISymbolDefinitionNode[] { this }); // Ensure the native layout data has been saved, in order to get valid Vertex offsets for the signature Vertices factory.MetadataManager.NativeLayoutInfo.SaveNativeLayoutInfoWriter(factory); NativeWriter nativeWriter = new NativeWriter(); VertexHashtable hashtable = new VertexHashtable(); Section nativeSection = nativeWriter.NewSection(); nativeSection.Place(hashtable); foreach (MethodDesc method in factory.MetadataManager.GetCompiledMethods()) { if (!IsMethodEligibleForTracking(factory, method)) continue; // Get the method pointer vertex bool getUnboxingStub = method.OwningType.IsValueType && !method.Signature.IsStatic; IMethodNode methodEntryPointNode = factory.MethodEntrypoint(method, getUnboxingStub); Vertex methodPointer = nativeWriter.GetUnsignedConstant(_externalReferences.GetIndex(methodEntryPointNode)); // Get native layout vertices for the declaring type ISymbolNode declaringTypeNode = factory.NecessaryTypeSymbol(method.OwningType); Vertex declaringType = nativeWriter.GetUnsignedConstant(_externalReferences.GetIndex(declaringTypeNode)); // Get a vertex sequence for the method instantiation args if any VertexSequence arguments = new VertexSequence(); foreach (var arg in method.Instantiation) { ISymbolNode argNode = factory.NecessaryTypeSymbol(arg); arguments.Append(nativeWriter.GetUnsignedConstant(_externalReferences.GetIndex(argNode))); } // Get the name and sig of the method. // Note: the method name and signature are stored in the NativeLayoutInfo blob, not in the hashtable we build here. NativeLayoutMethodNameAndSignatureVertexNode nameAndSig = factory.NativeLayout.MethodNameAndSignatureVertex(method.GetTypicalMethodDefinition()); NativeLayoutPlacedSignatureVertexNode placedNameAndSig = factory.NativeLayout.PlacedSignatureVertex(nameAndSig); Debug.Assert(placedNameAndSig.SavedVertex != null); Vertex placedNameAndSigOffsetSig = nativeWriter.GetOffsetSignature(placedNameAndSig.SavedVertex); // Get the vertex for the completed method signature Vertex methodSignature = nativeWriter.GetTuple(declaringType, placedNameAndSigOffsetSig, arguments); // Make the generic method entry vertex Vertex entry = nativeWriter.GetTuple(methodSignature, methodPointer); // Add to the hash table, hashed by the containing type's hashcode uint hashCode = (uint)method.OwningType.GetHashCode(); hashtable.Append(hashCode, nativeSection.Place(entry)); } byte[] streamBytes = nativeWriter.Save(); _endSymbol.SetSymbolOffset(streamBytes.Length); return new ObjectData(streamBytes, Array.Empty<Relocation>(), 1, new ISymbolDefinitionNode[] { this, _endSymbol }); } public static void GetExactMethodInstantiationDependenciesForMethod(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) { if (!IsMethodEligibleForTracking(factory, method)) return; dependencies = dependencies ?? new DependencyList(); // Method entry point dependency bool getUnboxingStub = method.OwningType.IsValueType && !method.Signature.IsStatic; IMethodNode methodEntryPointNode = factory.MethodEntrypoint(method, getUnboxingStub); dependencies.Add(new DependencyListEntry(methodEntryPointNode, "Exact method instantiation entry")); // Get native layout dependencies for the declaring type dependencies.Add(new DependencyListEntry(factory.NecessaryTypeSymbol(method.OwningType), "Exact method instantiation entry")); // Get native layout dependencies for the method instantiation args foreach (var arg in method.Instantiation) dependencies.Add(new DependencyListEntry(factory.NecessaryTypeSymbol(arg), "Exact method instantiation entry")); // Get native layout dependencies for the method signature. NativeLayoutMethodNameAndSignatureVertexNode nameAndSig = factory.NativeLayout.MethodNameAndSignatureVertex(method.GetTypicalMethodDefinition()); dependencies.Add(new DependencyListEntry(factory.NativeLayout.PlacedSignatureVertex(nameAndSig), "Exact method instantiation entry")); } private static bool IsMethodEligibleForTracking(NodeFactory factory, MethodDesc method) { // Runtime determined methods should never show up here. Debug.Assert(!method.IsRuntimeDeterminedExactMethod); if (method.IsAbstract) return false; if (!method.HasInstantiation) return false; // This hashtable is only for method instantiations that don't use generic dictionaries, // so check if the given method is shared before proceeding if (method.IsSharedByGenericInstantiations || method.GetCanonMethodTarget(CanonicalFormKind.Specific) != method) return false; // The hashtable is used to find implementations of generic virtual methods at runtime if (method.IsVirtual) return true; // The hashtable is also used for reflection if (!factory.MetadataManager.IsReflectionBlocked(method)) return true; // The rest of the entries are potentially only useful for the universal // canonical type loader. return factory.TypeSystemContext.SupportsUniversalCanon; } protected internal override int Phase => (int)ObjectNodePhase.Ordered; public override int ClassCode => (int)ObjectNodeOrder.ExactMethodInstantiationsNode; } }
-1