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,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.Generated.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.Dynamic; using System.Dynamic.Utils; using System.Reflection; using System.Threading; namespace System.Linq.Expressions.Interpreter { internal partial class CallInstruction { private const int MaxHelpers = 5; #if FEATURE_FAST_CREATE private const int MaxArgs = 3; /// <summary> /// Fast creation works if we have a known primitive types for the entire /// method signature. If we have any non-primitive types then FastCreate /// falls back to SlowCreate which works for all types. /// /// Fast creation is fast because it avoids using reflection (MakeGenericType /// and Activator.CreateInstance) to create the types. It does this through /// calling a series of generic methods picking up each strong type of the /// signature along the way. When it runs out of types it news up the /// appropriate CallInstruction with the strong-types that have been built up. /// /// One relaxation is that for return types which are non-primitive types /// we can fall back to object due to relaxed delegates. /// </summary> private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 0); if (t == null) { return new ActionCallInstruction(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(0, target, pi) || t.IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<Object>(target, pi); } case TypeCode.Int16: return FastCreate<Int16>(target, pi); case TypeCode.Int32: return FastCreate<Int32>(target, pi); case TypeCode.Int64: return FastCreate<Int64>(target, pi); case TypeCode.Boolean: return FastCreate<Boolean>(target, pi); case TypeCode.Char: return FastCreate<Char>(target, pi); case TypeCode.Byte: return FastCreate<Byte>(target, pi); case TypeCode.Decimal: return FastCreate<Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<DateTime>(target, pi); case TypeCode.Double: return FastCreate<Double>(target, pi); case TypeCode.Single: return FastCreate<Single>(target, pi); case TypeCode.UInt16: return FastCreate<UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<UInt64>(target, pi); case TypeCode.String: return FastCreate<String>(target, pi); case TypeCode.SByte: return FastCreate<SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 1); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0>(target); } return new FuncCallInstruction<T0>(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(1, target, pi) || t.IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<T0, Object>(target, pi); } case TypeCode.Int16: return FastCreate<T0, Int16>(target, pi); case TypeCode.Int32: return FastCreate<T0, Int32>(target, pi); case TypeCode.Int64: return FastCreate<T0, Int64>(target, pi); case TypeCode.Boolean: return FastCreate<T0, Boolean>(target, pi); case TypeCode.Char: return FastCreate<T0, Char>(target, pi); case TypeCode.Byte: return FastCreate<T0, Byte>(target, pi); case TypeCode.Decimal: return FastCreate<T0, Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<T0, DateTime>(target, pi); case TypeCode.Double: return FastCreate<T0, Double>(target, pi); case TypeCode.Single: return FastCreate<T0, Single>(target, pi); case TypeCode.UInt16: return FastCreate<T0, UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<T0, UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<T0, UInt64>(target, pi); case TypeCode.String: return FastCreate<T0, String>(target, pi); case TypeCode.SByte: return FastCreate<T0, SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0, T1>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 2); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0, T1>(target); } return new FuncCallInstruction<T0, T1>(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { Debug.Assert(pi.Length == 2); if (t.IsValueType) goto default; return new FuncCallInstruction<T0, T1, Object>(target); } case TypeCode.Int16: return new FuncCallInstruction<T0, T1, Int16>(target); case TypeCode.Int32: return new FuncCallInstruction<T0, T1, Int32>(target); case TypeCode.Int64: return new FuncCallInstruction<T0, T1, Int64>(target); case TypeCode.Boolean: return new FuncCallInstruction<T0, T1, Boolean>(target); case TypeCode.Char: return new FuncCallInstruction<T0, T1, Char>(target); case TypeCode.Byte: return new FuncCallInstruction<T0, T1, Byte>(target); case TypeCode.Decimal: return new FuncCallInstruction<T0, T1, Decimal>(target); case TypeCode.DateTime: return new FuncCallInstruction<T0, T1, DateTime>(target); case TypeCode.Double: return new FuncCallInstruction<T0, T1, Double>(target); case TypeCode.Single: return new FuncCallInstruction<T0, T1, Single>(target); case TypeCode.UInt16: return new FuncCallInstruction<T0, T1, UInt16>(target); case TypeCode.UInt32: return new FuncCallInstruction<T0, T1, UInt32>(target); case TypeCode.UInt64: return new FuncCallInstruction<T0, T1, UInt64>(target); case TypeCode.String: return new FuncCallInstruction<T0, T1, String>(target); case TypeCode.SByte: return new FuncCallInstruction<T0, T1, SByte>(target); default: return SlowCreate(target, pi); } } #endif [return: DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes.PublicConstructors)] private static Type GetHelperType(MethodInfo info, Type[] arrTypes) { Type t; if (info.ReturnType == typeof(void)) { switch (arrTypes.Length) { case 0: t = typeof(ActionCallInstruction); break; case 1: t = typeof(ActionCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(ActionCallInstruction<,>).MakeGenericType(arrTypes); break; case 3: t = typeof(ActionCallInstruction<,,>).MakeGenericType(arrTypes); break; case 4: t = typeof(ActionCallInstruction<,,,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } else { switch (arrTypes.Length) { case 1: t = typeof(FuncCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(FuncCallInstruction<,>).MakeGenericType(arrTypes); break; case 3: t = typeof(FuncCallInstruction<,,>).MakeGenericType(arrTypes); break; case 4: t = typeof(FuncCallInstruction<,,,>).MakeGenericType(arrTypes); break; case 5: t = typeof(FuncCallInstruction<,,,,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } return t; } } internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override int ArgumentCount => 0; public override int ProducedStack => 0; public ActionCallInstruction(MethodInfo target) { _target = (Action)target.CreateDelegate(typeof(Action)); } public override int Run(InterpretedFrame frame) { _target(); frame.StackIndex -= 0; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0> _target; public override int ProducedStack => 0; public override int ArgumentCount => 1; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0>)target.CreateDelegate(typeof(Action<T0>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 1]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, Array.Empty<object>()); } else { _target((T0)firstArg); } frame.StackIndex -= 1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1> _target; public override int ProducedStack => 0; public override int ArgumentCount => 2; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1>)target.CreateDelegate(typeof(Action<T0, T1>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 2]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 2; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1, T2> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1, T2> _target; public override int ProducedStack => 0; public override int ArgumentCount => 3; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1, T2>)target.CreateDelegate(typeof(Action<T0, T1, T2>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 3]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 3; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1, T2, T3> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1, T2, T3> _target; public override int ProducedStack => 0; public override int ArgumentCount => 4; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1, T2, T3>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 4]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 4; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<TRet> : CallInstruction { private readonly Func<TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 0; public FuncCallInstruction(MethodInfo target) { _target = (Func<TRet>)target.CreateDelegate(typeof(Func<TRet>)); } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex - 0] = _target(); frame.StackIndex -= -1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 1; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, TRet>)target.CreateDelegate(typeof(Func<T0, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 1]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, Array.Empty<object>()); } else { result = _target((T0)firstArg); } frame.Data[frame.StackIndex - 1] = result; frame.StackIndex -= 0; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 2; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, TRet>)target.CreateDelegate(typeof(Func<T0, T1, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 2]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 2] = result; frame.StackIndex -= 1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, T2, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, T2, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 3; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, T2, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 3]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 3] = result; frame.StackIndex -= 2; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, T2, T3, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, T2, T3, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 4; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, T2, T3, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 4]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 4] = result; frame.StackIndex -= 3; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } }
// 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.Dynamic; using System.Dynamic.Utils; using System.Reflection; using System.Threading; namespace System.Linq.Expressions.Interpreter { internal partial class CallInstruction { private const int MaxHelpers = 5; #if FEATURE_FAST_CREATE private const int MaxArgs = 3; /// <summary> /// Fast creation works if we have a known primitive types for the entire /// method signature. If we have any non-primitive types then FastCreate /// falls back to SlowCreate which works for all types. /// /// Fast creation is fast because it avoids using reflection (MakeGenericType /// and Activator.CreateInstance) to create the types. It does this through /// calling a series of generic methods picking up each strong type of the /// signature along the way. When it runs out of types it news up the /// appropriate CallInstruction with the strong-types that have been built up. /// /// One relaxation is that for return types which are non-primitive types /// we can fall back to object due to relaxed delegates. /// </summary> private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 0); if (t == null) { return new ActionCallInstruction(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(0, target, pi) || t.IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<Object>(target, pi); } case TypeCode.Int16: return FastCreate<Int16>(target, pi); case TypeCode.Int32: return FastCreate<Int32>(target, pi); case TypeCode.Int64: return FastCreate<Int64>(target, pi); case TypeCode.Boolean: return FastCreate<Boolean>(target, pi); case TypeCode.Char: return FastCreate<Char>(target, pi); case TypeCode.Byte: return FastCreate<Byte>(target, pi); case TypeCode.Decimal: return FastCreate<Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<DateTime>(target, pi); case TypeCode.Double: return FastCreate<Double>(target, pi); case TypeCode.Single: return FastCreate<Single>(target, pi); case TypeCode.UInt16: return FastCreate<UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<UInt64>(target, pi); case TypeCode.String: return FastCreate<String>(target, pi); case TypeCode.SByte: return FastCreate<SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 1); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0>(target); } return new FuncCallInstruction<T0>(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(1, target, pi) || t.IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<T0, Object>(target, pi); } case TypeCode.Int16: return FastCreate<T0, Int16>(target, pi); case TypeCode.Int32: return FastCreate<T0, Int32>(target, pi); case TypeCode.Int64: return FastCreate<T0, Int64>(target, pi); case TypeCode.Boolean: return FastCreate<T0, Boolean>(target, pi); case TypeCode.Char: return FastCreate<T0, Char>(target, pi); case TypeCode.Byte: return FastCreate<T0, Byte>(target, pi); case TypeCode.Decimal: return FastCreate<T0, Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<T0, DateTime>(target, pi); case TypeCode.Double: return FastCreate<T0, Double>(target, pi); case TypeCode.Single: return FastCreate<T0, Single>(target, pi); case TypeCode.UInt16: return FastCreate<T0, UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<T0, UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<T0, UInt64>(target, pi); case TypeCode.String: return FastCreate<T0, String>(target, pi); case TypeCode.SByte: return FastCreate<T0, SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0, T1>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 2); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0, T1>(target); } return new FuncCallInstruction<T0, T1>(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { Debug.Assert(pi.Length == 2); if (t.IsValueType) goto default; return new FuncCallInstruction<T0, T1, Object>(target); } case TypeCode.Int16: return new FuncCallInstruction<T0, T1, Int16>(target); case TypeCode.Int32: return new FuncCallInstruction<T0, T1, Int32>(target); case TypeCode.Int64: return new FuncCallInstruction<T0, T1, Int64>(target); case TypeCode.Boolean: return new FuncCallInstruction<T0, T1, Boolean>(target); case TypeCode.Char: return new FuncCallInstruction<T0, T1, Char>(target); case TypeCode.Byte: return new FuncCallInstruction<T0, T1, Byte>(target); case TypeCode.Decimal: return new FuncCallInstruction<T0, T1, Decimal>(target); case TypeCode.DateTime: return new FuncCallInstruction<T0, T1, DateTime>(target); case TypeCode.Double: return new FuncCallInstruction<T0, T1, Double>(target); case TypeCode.Single: return new FuncCallInstruction<T0, T1, Single>(target); case TypeCode.UInt16: return new FuncCallInstruction<T0, T1, UInt16>(target); case TypeCode.UInt32: return new FuncCallInstruction<T0, T1, UInt32>(target); case TypeCode.UInt64: return new FuncCallInstruction<T0, T1, UInt64>(target); case TypeCode.String: return new FuncCallInstruction<T0, T1, String>(target); case TypeCode.SByte: return new FuncCallInstruction<T0, T1, SByte>(target); default: return SlowCreate(target, pi); } } #endif [return: DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes.PublicConstructors)] private static Type GetHelperType(MethodInfo info, Type[] arrTypes) { Type t; if (info.ReturnType == typeof(void)) { switch (arrTypes.Length) { case 0: t = typeof(ActionCallInstruction); break; case 1: t = typeof(ActionCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(ActionCallInstruction<,>).MakeGenericType(arrTypes); break; case 3: t = typeof(ActionCallInstruction<,,>).MakeGenericType(arrTypes); break; case 4: t = typeof(ActionCallInstruction<,,,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } else { switch (arrTypes.Length) { case 1: t = typeof(FuncCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(FuncCallInstruction<,>).MakeGenericType(arrTypes); break; case 3: t = typeof(FuncCallInstruction<,,>).MakeGenericType(arrTypes); break; case 4: t = typeof(FuncCallInstruction<,,,>).MakeGenericType(arrTypes); break; case 5: t = typeof(FuncCallInstruction<,,,,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } return t; } } internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override int ArgumentCount => 0; public override int ProducedStack => 0; public ActionCallInstruction(MethodInfo target) { _target = (Action)target.CreateDelegate(typeof(Action)); } public override int Run(InterpretedFrame frame) { _target(); frame.StackIndex -= 0; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0> _target; public override int ProducedStack => 0; public override int ArgumentCount => 1; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0>)target.CreateDelegate(typeof(Action<T0>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 1]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, Array.Empty<object>()); } else { _target((T0)firstArg); } frame.StackIndex -= 1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1> _target; public override int ProducedStack => 0; public override int ArgumentCount => 2; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1>)target.CreateDelegate(typeof(Action<T0, T1>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 2]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 2; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1, T2> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1, T2> _target; public override int ProducedStack => 0; public override int ArgumentCount => 3; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1, T2>)target.CreateDelegate(typeof(Action<T0, T1, T2>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 3]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 3; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1, T2, T3> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1, T2, T3> _target; public override int ProducedStack => 0; public override int ArgumentCount => 4; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1, T2, T3>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 4]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 4; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<TRet> : CallInstruction { private readonly Func<TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 0; public FuncCallInstruction(MethodInfo target) { _target = (Func<TRet>)target.CreateDelegate(typeof(Func<TRet>)); } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex - 0] = _target(); frame.StackIndex -= -1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 1; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, TRet>)target.CreateDelegate(typeof(Func<T0, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 1]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, Array.Empty<object>()); } else { result = _target((T0)firstArg); } frame.Data[frame.StackIndex - 1] = result; frame.StackIndex -= 0; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 2; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, TRet>)target.CreateDelegate(typeof(Func<T0, T1, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 2]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 2] = result; frame.StackIndex -= 1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, T2, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, T2, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 3; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, T2, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 3]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 3] = result; frame.StackIndex -= 2; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, T2, T3, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, T2, T3, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 4; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, T2, T3, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 4]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 4] = result; frame.StackIndex -= 3; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Net.Mail/tests/Functional/SmtpClientCredentialsTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Mail.Functional.Tests { [SkipOnPlatform(TestPlatforms.Browser, "SmtpClient is not supported on Browser")] public class SmtpClientCredentialsTest { private readonly string UserName = "user"; private readonly string Password = Guid.NewGuid().ToString(); [Fact] public void Credentials_Unset_Null() { SmtpClient client = new SmtpClient(); ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Null(client.Credentials); Assert.Null(transportCredentials); } [Fact] public void DefaultCredentials_True_DefaultCredentials() { NetworkCredential expectedCredentials = CredentialCache.DefaultNetworkCredentials; SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = true; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void UseDefaultCredentials_False_Null() { SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = false; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Null(client.Credentials); Assert.Null(transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetFalseBeforeCredentials_Credentials() { NetworkCredential expectedCredentials = new NetworkCredential(UserName, Password); SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = false; client.Credentials = expectedCredentials; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.NotNull(client.Credentials); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetFalseAfterCredentials_Credentials() { NetworkCredential expectedCredentials = new NetworkCredential(UserName, Password); SmtpClient client = new SmtpClient(); client.Credentials = expectedCredentials; client.UseDefaultCredentials = false; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.NotNull(client.Credentials); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetTrueBeforeCredentials_DefaultNetworkCredentials() { NetworkCredential expectedCredentials = CredentialCache.DefaultNetworkCredentials; SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = true; client.Credentials = new NetworkCredential(UserName, Password); ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetTrueAfterCredentials_DefaultNetworkCredentials() { NetworkCredential expectedCredentials = CredentialCache.DefaultNetworkCredentials; SmtpClient client = new SmtpClient(); client.Credentials = new NetworkCredential(UserName, Password); client.UseDefaultCredentials = true; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } private ICredentialsByHost GetTransportCredentials(SmtpClient client) { Type smtpTransportType = (typeof(SmtpClient)).Assembly.GetType("System.Net.Mail.SmtpTransport"); var transport = typeof(SmtpClient) .GetField("_transport", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance) .GetValue(client); var transportCredentials = smtpTransportType .GetProperty("Credentials", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance) .GetValue(transport); return (ICredentialsByHost)transportCredentials; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Mail.Functional.Tests { [SkipOnPlatform(TestPlatforms.Browser, "SmtpClient is not supported on Browser")] public class SmtpClientCredentialsTest { private readonly string UserName = "user"; private readonly string Password = Guid.NewGuid().ToString(); [Fact] public void Credentials_Unset_Null() { SmtpClient client = new SmtpClient(); ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Null(client.Credentials); Assert.Null(transportCredentials); } [Fact] public void DefaultCredentials_True_DefaultCredentials() { NetworkCredential expectedCredentials = CredentialCache.DefaultNetworkCredentials; SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = true; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void UseDefaultCredentials_False_Null() { SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = false; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Null(client.Credentials); Assert.Null(transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetFalseBeforeCredentials_Credentials() { NetworkCredential expectedCredentials = new NetworkCredential(UserName, Password); SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = false; client.Credentials = expectedCredentials; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.NotNull(client.Credentials); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetFalseAfterCredentials_Credentials() { NetworkCredential expectedCredentials = new NetworkCredential(UserName, Password); SmtpClient client = new SmtpClient(); client.Credentials = expectedCredentials; client.UseDefaultCredentials = false; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.NotNull(client.Credentials); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetTrueBeforeCredentials_DefaultNetworkCredentials() { NetworkCredential expectedCredentials = CredentialCache.DefaultNetworkCredentials; SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = true; client.Credentials = new NetworkCredential(UserName, Password); ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } [Fact] public void Credentials_UseDefaultCredentialsSetTrueAfterCredentials_DefaultNetworkCredentials() { NetworkCredential expectedCredentials = CredentialCache.DefaultNetworkCredentials; SmtpClient client = new SmtpClient(); client.Credentials = new NetworkCredential(UserName, Password); client.UseDefaultCredentials = true; ICredentialsByHost transportCredentials = GetTransportCredentials(client); Assert.Equal(expectedCredentials, client.Credentials); Assert.Equal(expectedCredentials, transportCredentials); } private ICredentialsByHost GetTransportCredentials(SmtpClient client) { Type smtpTransportType = (typeof(SmtpClient)).Assembly.GetType("System.Net.Mail.SmtpTransport"); var transport = typeof(SmtpClient) .GetField("_transport", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance) .GetValue(client); var transportCredentials = smtpTransportType .GetProperty("Credentials", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance) .GetValue(transport); return (ICredentialsByHost)transportCredentials; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyBySelectedScalarWideningUpperAndAdd.Vector128.UInt16.Vector64.UInt16.3.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 MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3() { var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3 { 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, UInt16[] inArray2, UInt16[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt16, 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<UInt16> _fld2; public Vector64<UInt16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3 testClass) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(_fld1, _fld2, _fld3, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); 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<UInt16>>() / sizeof(UInt16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 3; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static UInt16[] _data3 = new UInt16[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt16> _clsVar2; private static Vector64<UInt16> _clsVar3; private Vector128<UInt32> _fld1; private Vector128<UInt16> _fld2; private Vector64<UInt16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, 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.MultiplyBySelectedScalarWideningUpperAndAdd( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), (byte)3 }); 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(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), (byte)3 }); 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 = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( _clsVar1, _clsVar2, _clsVar3, 3 ); 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<UInt16>* pClsVar2 = &_clsVar2) fixed (Vector64<UInt16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt16*)(pClsVar2)), AdvSimd.LoadVector64((UInt16*)(pClsVar3)), 3 ); 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<UInt16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(op1, op2, op3, 3); 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((UInt16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(op1, op2, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3(); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) fixed (Vector64<UInt16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(_fld1, _fld2, _fld3, 3); 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<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt16*)(&test._fld2)), AdvSimd.LoadVector64((UInt16*)(&test._fld3)), 3 ); 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<UInt16> op2, Vector64<UInt16> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, 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]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[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<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); 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, UInt16[] secondOp, UInt16[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyByScalarWideningUpperAndAdd(firstOp, secondOp, thirdOp[Imm], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd)}<UInt32>(Vector128<UInt32>, Vector128<UInt16>, Vector64<UInt16>): {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 MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3() { var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3 { 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, UInt16[] inArray2, UInt16[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt16, 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<UInt16> _fld2; public Vector64<UInt16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3 testClass) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(_fld1, _fld2, _fld3, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); 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<UInt16>>() / sizeof(UInt16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 3; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static UInt16[] _data3 = new UInt16[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt16> _clsVar2; private static Vector64<UInt16> _clsVar3; private Vector128<UInt32> _fld1; private Vector128<UInt16> _fld2; private Vector64<UInt16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, 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.MultiplyBySelectedScalarWideningUpperAndAdd( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), (byte)3 }); 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(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), (byte)3 }); 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 = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( _clsVar1, _clsVar2, _clsVar3, 3 ); 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<UInt16>* pClsVar2 = &_clsVar2) fixed (Vector64<UInt16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt16*)(pClsVar2)), AdvSimd.LoadVector64((UInt16*)(pClsVar3)), 3 ); 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<UInt16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(op1, op2, op3, 3); 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((UInt16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(op1, op2, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3(); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndAdd_Vector128_UInt16_Vector64_UInt16_3(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) fixed (Vector64<UInt16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(_fld1, _fld2, _fld3, 3); 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<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt16*)(&test._fld2)), AdvSimd.LoadVector64((UInt16*)(&test._fld3)), 3 ); 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<UInt16> op2, Vector64<UInt16> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, 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]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[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<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); 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, UInt16[] secondOp, UInt16[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyByScalarWideningUpperAndAdd(firstOp, secondOp, thirdOp[Imm], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndAdd)}<UInt32>(Vector128<UInt32>, Vector128<UInt16>, Vector64<UInt16>): {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,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/Subtract.Int16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 SubtractInt16() { var test = new SimpleBinaryOpTest__SubtractInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractInt16 testClass) { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractInt16 testClass) { fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public SimpleBinaryOpTest__SubtractInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Subtract( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Subtract( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(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.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(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.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int16>* pClsVar1 = &_clsVar1) fixed (Vector256<Int16>* pClsVar2 = &_clsVar2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pClsVar1)), Avx.LoadVector256((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractInt16(); var result = Avx2.Subtract(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__SubtractInt16(); fixed (Vector256<Int16>* pFld1 = &test._fld1) fixed (Vector256<Int16>* pFld2 = &test._fld2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(&test._fld1)), Avx.LoadVector256((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] - right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] - right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 SubtractInt16() { var test = new SimpleBinaryOpTest__SubtractInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractInt16 testClass) { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractInt16 testClass) { fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public SimpleBinaryOpTest__SubtractInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Subtract( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Subtract( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(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.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(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.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int16>* pClsVar1 = &_clsVar1) fixed (Vector256<Int16>* pClsVar2 = &_clsVar2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pClsVar1)), Avx.LoadVector256((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractInt16(); var result = Avx2.Subtract(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__SubtractInt16(); fixed (Vector256<Int16>* pFld1 = &test._fld1) fixed (Vector256<Int16>* pFld2 = &test._fld2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Subtract( Avx.LoadVector256((Int16*)(&test._fld1)), Avx.LoadVector256((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] - right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] - right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/jit64/opt/cg/CGRecurse/CGRecurseACC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace CGRecurse { public class RecursiveACC { public static string ActualResult; public static int cntA = 0; public static int cntB = 0; public static int cntC = 0; public static int Main() { string ExpectedResult = "ACC"; int retVal = 1; A(); Console.WriteLine(ActualResult); if (ExpectedResult.Equals(ActualResult)) { Console.WriteLine("Test SUCCESS"); retVal = 100; } return retVal; } public static void C() { ActualResult = (ActualResult + "C"); if ((cntC == 2)) { cntC = 0; return; } cntC = (cntC + 1); C(); return; } public static void A() { ActualResult = (ActualResult + "A"); if ((cntC == 1)) { cntC = 0; return; } cntC = (cntC + 1); C(); return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace CGRecurse { public class RecursiveACC { public static string ActualResult; public static int cntA = 0; public static int cntB = 0; public static int cntC = 0; public static int Main() { string ExpectedResult = "ACC"; int retVal = 1; A(); Console.WriteLine(ActualResult); if (ExpectedResult.Equals(ActualResult)) { Console.WriteLine("Test SUCCESS"); retVal = 100; } return retVal; } public static void C() { ActualResult = (ActualResult + "C"); if ((cntC == 2)) { cntC = 0; return; } cntC = (cntC + 1); C(); return; } public static void A() { ActualResult = (ActualResult + "A"); if ((cntC == 1)) { cntC = 0; return; } cntC = (cntC + 1); C(); return; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Methodical/eh/basics/throwincatch.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Throw in catch handler using System; namespace hello { class Class1 { private static TestUtil.TestLog testLog; static Class1() { // Create test writer object to hold expected output System.IO.StringWriter expectedOut = new System.IO.StringWriter(); // Write expected output to string writer object expectedOut.WriteLine("In try"); expectedOut.WriteLine("In try 2, 1st throw"); expectedOut.WriteLine("In 1st catch, 2nd throw"); expectedOut.WriteLine("In 2nd catch"); expectedOut.WriteLine("Done"); // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } static public int Main() { //Start recording testLog.StartRecording(); try { try { Console.WriteLine("In try"); try { Console.WriteLine("In try 2, 1st throw"); throw new Exception(); } catch { Console.WriteLine("In 1st catch, 2nd throw"); throw new Exception(); } } catch { Console.WriteLine("In 2nd catch"); } } catch { Console.WriteLine("Unreached"); } Console.WriteLine("Done"); // stop recoding testLog.StopRecording(); return testLog.VerifyOutput(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Throw in catch handler using System; namespace hello { class Class1 { private static TestUtil.TestLog testLog; static Class1() { // Create test writer object to hold expected output System.IO.StringWriter expectedOut = new System.IO.StringWriter(); // Write expected output to string writer object expectedOut.WriteLine("In try"); expectedOut.WriteLine("In try 2, 1st throw"); expectedOut.WriteLine("In 1st catch, 2nd throw"); expectedOut.WriteLine("In 2nd catch"); expectedOut.WriteLine("Done"); // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } static public int Main() { //Start recording testLog.StartRecording(); try { try { Console.WriteLine("In try"); try { Console.WriteLine("In try 2, 1st throw"); throw new Exception(); } catch { Console.WriteLine("In 1st catch, 2nd throw"); throw new Exception(); } } catch { Console.WriteLine("In 2nd catch"); } } catch { Console.WriteLine("Unreached"); } Console.WriteLine("Done"); // stop recoding testLog.StopRecording(); return testLog.VerifyOutput(); } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueryResult.Enumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace System.Reflection.Runtime.BindingFlagSupport { internal partial struct QueryResult<M> where M : MemberInfo { internal struct QueryResultEnumerator { public QueryResultEnumerator(QueryResult<M> queryResult) { _bindingAttr = queryResult._bindingAttr; _unfilteredCount = queryResult.UnfilteredCount; _queriedMembers = queryResult._queriedMembers; _index = -1; } public bool MoveNext() { while (++_index < _unfilteredCount && !_queriedMembers.Matches(_index, _bindingAttr)) { } if (_index < _unfilteredCount) return true; _index = _unfilteredCount; // guard against wiseguys calling MoveNext() over and over after the end. return false; } public M Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _queriedMembers[_index]; } } private int _index; private readonly int _unfilteredCount; private readonly BindingFlags _bindingAttr; private readonly QueriedMemberList<M> _queriedMembers; } } }
// 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.Collections.Generic; using System.Runtime.CompilerServices; namespace System.Reflection.Runtime.BindingFlagSupport { internal partial struct QueryResult<M> where M : MemberInfo { internal struct QueryResultEnumerator { public QueryResultEnumerator(QueryResult<M> queryResult) { _bindingAttr = queryResult._bindingAttr; _unfilteredCount = queryResult.UnfilteredCount; _queriedMembers = queryResult._queriedMembers; _index = -1; } public bool MoveNext() { while (++_index < _unfilteredCount && !_queriedMembers.Matches(_index, _bindingAttr)) { } if (_index < _unfilteredCount) return true; _index = _unfilteredCount; // guard against wiseguys calling MoveNext() over and over after the end. return false; } public M Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _queriedMembers[_index]; } } private int _index; private readonly int _unfilteredCount; private readonly BindingFlags _bindingAttr; private readonly QueriedMemberList<M> _queriedMembers; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/jit64/gc/misc/struct6_5.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; #pragma warning restore 0414 } struct S { public String str; #pragma warning disable 0414 public Pad pad; public Pad pad2; public Pad pad3; public Pad pad4; public Pad pad5; public String str2; #pragma warning restore 0414 Pad initPad() { Pad p; p.d1 = p.d2 = p.d3 = p.d4 = p.d5 = p.d6 = p.d7 = p.d8 = p.d9 = p.d10 = p.d11 = p.d12 = p.d13 = p.d14 = p.d15 = p.d16 = p.d17 = p.d18 = p.d19 = p.d20 = p.d21 = p.d22 = p.d23 = p.d24 = p.d25 = p.d26 = p.d27 = p.d28 = p.d29 = p.d30 = 3.3; return p; } public S(String s) { str = s; str2 = s + str; //pad = initPad(); pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; pad5 = pad4 = pad3 = pad2 = pad; } } class Test_struct6_5 { public static void c(S s1, S s2, S s3, S s4, S s5) { Console.WriteLine(s1.str + s2.str + s3.str + s4.str + s5.str); } public static int Main() { S sM = new S("test"); S sM2 = new S("test2"); S sM3 = new S("test3"); S sM4 = new S("test4"); S sM5 = new S("test5"); c(sM, sM2, sM3, sM4, sM5); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; #pragma warning restore 0414 } struct S { public String str; #pragma warning disable 0414 public Pad pad; public Pad pad2; public Pad pad3; public Pad pad4; public Pad pad5; public String str2; #pragma warning restore 0414 Pad initPad() { Pad p; p.d1 = p.d2 = p.d3 = p.d4 = p.d5 = p.d6 = p.d7 = p.d8 = p.d9 = p.d10 = p.d11 = p.d12 = p.d13 = p.d14 = p.d15 = p.d16 = p.d17 = p.d18 = p.d19 = p.d20 = p.d21 = p.d22 = p.d23 = p.d24 = p.d25 = p.d26 = p.d27 = p.d28 = p.d29 = p.d30 = 3.3; return p; } public S(String s) { str = s; str2 = s + str; //pad = initPad(); pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; pad5 = pad4 = pad3 = pad2 = pad; } } class Test_struct6_5 { public static void c(S s1, S s2, S s3, S s4, S s5) { Console.WriteLine(s1.str + s2.str + s3.str + s4.str + s5.str); } public static int Main() { S sM = new S("test"); S sM2 = new S("test2"); S sM3 = new S("test3"); S sM4 = new S("test4"); S sM5 = new S("test5"); c(sM, sM2, sM3, sM4, sM5); return 100; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/General/Vector128/Negate.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void NegateDouble() { var test = new VectorUnaryOpTest__NegateDouble(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorUnaryOpTest__NegateDouble { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__NegateDouble testClass) { var result = Vector128.Negate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__NegateDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public VectorUnaryOpTest__NegateDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Negate( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Negate), new Type[] { typeof(Vector128<Double>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Negate), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Double)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Negate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var result = Vector128.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__NegateDouble(); var result = Vector128.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Negate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (double)(0 - firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (double)(0 - firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Negate)}<Double>(Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void NegateDouble() { var test = new VectorUnaryOpTest__NegateDouble(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorUnaryOpTest__NegateDouble { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__NegateDouble testClass) { var result = Vector128.Negate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__NegateDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public VectorUnaryOpTest__NegateDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Negate( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Negate), new Type[] { typeof(Vector128<Double>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Negate), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Double)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Negate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var result = Vector128.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__NegateDouble(); var result = Vector128.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Negate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (double)(0 - firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (double)(0 - firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Negate)}<Double>(Vector128<Double>): {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,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.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.Xsl.XsltOld { using System.Diagnostics; using System.IO; using System.Globalization; using System.Collections; using System.Xml.XPath; using System.Xml.Xsl.Runtime; using MS.Internal.Xml.XPath; using System.Reflection; using System.Security; using System.Runtime.Versioning; using System.Diagnostics.CodeAnalysis; internal sealed class XsltCompileContext : XsltContext { private InputScopeManager? _manager; private Processor? _processor; // storage for the functions private static readonly Hashtable s_FunctionTable = CreateFunctionTable(); private static readonly IXsltContextFunction s_FuncNodeSet = new FuncNodeSet(); private const string f_NodeSet = "node-set"; internal XsltCompileContext(InputScopeManager manager, Processor processor) : base(/*dummy*/false) { _manager = manager; _processor = processor; } internal XsltCompileContext() : base(/*dummy*/ false) { } internal void Recycle() { _manager = null; _processor = null; } internal void Reinitialize(InputScopeManager manager, Processor processor) { _manager = manager; _processor = processor; } public override int CompareDocument(string baseUri, string nextbaseUri) { return string.Compare(baseUri, nextbaseUri, StringComparison.Ordinal); } // Namespace support public override string DefaultNamespace { get { return string.Empty; } } public override string LookupNamespace(string prefix) { return _manager!.ResolveXPathNamespace(prefix); } // --------------------------- XsltContext ------------------- // Resolving variables and functions public override IXsltContextVariable ResolveVariable(string prefix, string name) { string namespaceURI = this.LookupNamespace(prefix); XmlQualifiedName qname = new XmlQualifiedName(name, namespaceURI); IXsltContextVariable? variable = _manager!.VariableScope.ResolveVariable(qname); if (variable == null) { throw XsltException.Create(SR.Xslt_InvalidVariable, qname.ToString()); } return variable; } internal object EvaluateVariable(VariableAction variable) { object result = _processor!.GetVariableValue(variable); if (result == null && !variable.IsGlobal) { // This was uninitialized local variable. May be we have sutable global var too? VariableAction? global = _manager!.VariableScope.ResolveGlobalVariable(variable.Name!); if (global != null) { result = _processor.GetVariableValue(global); } } if (result == null) { throw XsltException.Create(SR.Xslt_InvalidVariable, variable.Name!.ToString()); } return result; } // Whitespace stripping support public override bool Whitespace { get { return _processor!.Stylesheet.Whitespace; } } public override bool PreserveWhitespace(XPathNavigator node) { node = node.Clone(); node.MoveToParent(); return _processor!.Stylesheet.PreserveWhiteSpace(_processor, node); } private MethodInfo? FindBestMethod(MethodInfo[] methods, bool ignoreCase, bool publicOnly, string name, XPathResultType[]? argTypes) { int length = methods.Length; int free = 0; // restrict search to methods with the same name and requiested protection attribute for (int i = 0; i < length; i++) { if (string.Equals(name, methods[i].Name, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { if (!publicOnly || methods[i].GetBaseDefinition().IsPublic) { methods[free++] = methods[i]; } } } length = free; if (length == 0) { // this is the only place we returning null in this function return null; } if (argTypes == null) { // without arg types we can't do more detailed search return methods[0]; } // restrict search by number of parameters free = 0; for (int i = 0; i < length; i++) { if (methods[i].GetParameters().Length == argTypes.Length) { methods[free++] = methods[i]; } } length = free; if (length <= 1) { // 0 -- not method found. We have to return non-null and let it fail with correct exception on call. // 1 -- no reason to continue search anyway. return methods[0]; } // restrict search by parameters type free = 0; for (int i = 0; i < length; i++) { bool match = true; ParameterInfo[] parameters = methods[i].GetParameters(); for (int par = 0; par < parameters.Length; par++) { XPathResultType required = argTypes[par]; if (required == XPathResultType.Any) { continue; // Any means we don't know type and can't discriminate by it } XPathResultType actual = GetXPathType(parameters[par].ParameterType); if ( actual != required && actual != XPathResultType.Any // actual arg is object and we can pass everithing here. ) { match = false; break; } } if (match) { methods[free++] = methods[i]; } } return methods[0]; } private const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:RequiresUnreferencedCode", Justification = XsltArgumentList.ExtensionObjectSuppresion)] private IXsltContextFunction? GetExtentionMethod(string ns, string name, XPathResultType[]? argTypes, out object? extension) { FuncExtension? result = null; extension = _processor!.GetScriptObject(ns); if (extension != null) { MethodInfo? method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/true, /*publicOnly:*/false, name, argTypes); if (method != null) { result = new FuncExtension(extension, method); } return result; } extension = _processor.GetExtensionObject(ns); if (extension != null) { MethodInfo? method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/false, /*publicOnly:*/true, name, argTypes); if (method != null) { result = new FuncExtension(extension, method); } return result; } return null; } public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] argTypes) { IXsltContextFunction? func; if (prefix.Length == 0) { func = s_FunctionTable[name] as IXsltContextFunction; } else { string ns = this.LookupNamespace(prefix); if (ns == XmlReservedNs.NsMsxsl && name == f_NodeSet) { func = s_FuncNodeSet; } else { object? extension; func = GetExtentionMethod(ns, name, argTypes, out extension); if (extension == null) { throw XsltException.Create(SR.Xslt_ScriptInvalidPrefix, prefix); // BugBug: It's better to say that method 'name' not found } } } if (func == null) { throw XsltException.Create(SR.Xslt_UnknownXsltFunction, name); } if (argTypes.Length < func.Minargs || func.Maxargs < argTypes.Length) { throw XsltException.Create(SR.Xslt_WrongNumberArgs, name, argTypes.Length.ToString(CultureInfo.InvariantCulture)); } return func; } // // Xslt Function Extensions to XPath // private Uri ComposeUri(string thisUri, string baseUri) { Debug.Assert(thisUri != null && baseUri != null); XmlResolver resolver = _processor!.Resolver; Uri? uriBase = null; if (baseUri.Length != 0) { uriBase = resolver.ResolveUri(null, baseUri); } return resolver.ResolveUri(uriBase, thisUri); } private XPathNodeIterator Document(object arg0, string? baseUri) { XPathNodeIterator? it = arg0 as XPathNodeIterator; if (it != null) { ArrayList list = new ArrayList(); Hashtable documents = new Hashtable(); while (it.MoveNext()) { Uri uri = ComposeUri(it.Current!.Value, baseUri ?? it.Current.BaseURI); if (!documents.ContainsKey(uri)) { documents.Add(uri, null); list.Add(_processor!.GetNavigator(uri)); } } return new XPathArrayIterator(list); } else { return new XPathSingletonIterator( _processor!.GetNavigator( ComposeUri(XmlConvert.ToXPathString(arg0)!, baseUri ?? _manager!.Navigator.BaseURI) ) ); } } private Hashtable BuildKeyTable(Key key, XPathNavigator root) { Hashtable keyTable = new Hashtable(); string matchStr = _processor!.GetQueryExpression(key.MatchKey); Query matchExpr = _processor.GetCompiledQuery(key.MatchKey); Query useExpr = _processor.GetCompiledQuery(key.UseKey); XPathNodeIterator sel = root.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ false); while (sel.MoveNext()) { XPathNavigator node = sel.Current!; EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable); if (node.MoveToFirstAttribute()) { do { EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable); } while (node.MoveToNextAttribute()); node.MoveToParent(); } } return keyTable; } private static void AddKeyValue(Hashtable keyTable, string key, XPathNavigator value, bool checkDuplicates) { ArrayList? list = (ArrayList?)keyTable[key]; if (list == null) { list = new ArrayList(); keyTable.Add(key, list); } else { Debug.Assert( value.ComparePosition((XPathNavigator?)list[list.Count - 1]) != XmlNodeOrder.Before, "The way we traversing nodes should garantees node-order" ); if (checkDuplicates) { // it's posible that this value already was assosiated with current node // but if this happened the node is last in the list of values. if (value.ComparePosition((XPathNavigator?)list[list.Count - 1]) == XmlNodeOrder.Same) { return; } } else { Debug.Assert( value.ComparePosition((XPathNavigator?)list[list.Count - 1]) != XmlNodeOrder.Same, "checkDuplicates == false : We can't have duplicates" ); } } list.Add(value.Clone()); } private static void EvaluateKey(XPathNavigator? node, Query matchExpr, string matchStr, Query useExpr, Hashtable keyTable) { try { if (matchExpr.MatchNode(node) == null) { return; } } catch (XPathException) { throw XsltException.Create(SR.Xslt_InvalidPattern, matchStr); } object result = useExpr.Evaluate(new XPathSingletonIterator(node!, /*moved:*/true)); XPathNodeIterator? it = result as XPathNodeIterator; if (it != null) { bool checkDuplicates = false; while (it.MoveNext()) { AddKeyValue(keyTable, /*key:*/it.Current!.Value!, /*value:*/node!, checkDuplicates); checkDuplicates = true; } } else { string key = XmlConvert.ToXPathString(result)!; AddKeyValue(keyTable, key, /*value:*/node!, /*checkDuplicates:*/ false); } } private DecimalFormat ResolveFormatName(string? formatName) { string ns = string.Empty, local = string.Empty; if (formatName != null) { string prefix; PrefixQName.ParseQualifiedName(formatName, out prefix, out local); ns = LookupNamespace(prefix); } DecimalFormat? formatInfo = _processor!.RootAction!.GetDecimalFormat(new XmlQualifiedName(local, ns)); if (formatInfo == null) { if (formatName != null) { throw XsltException.Create(SR.Xslt_NoDecimalFormat, formatName); } formatInfo = new DecimalFormat(new NumberFormatInfo(), '#', '0', ';'); } return formatInfo; } // see http://www.w3.org/TR/xslt#function-element-available private bool ElementAvailable(string qname) { string name, prefix; PrefixQName.ParseQualifiedName(qname, out prefix, out name); string ns = _manager!.ResolveXmlNamespace(prefix); // msxsl:script - is not an "instruction" so we return false for it. if (ns == XmlReservedNs.NsXslt) { return ( name == "apply-imports" || name == "apply-templates" || name == "attribute" || name == "call-template" || name == "choose" || name == "comment" || name == "copy" || name == "copy-of" || name == "element" || name == "fallback" || name == "for-each" || name == "if" || name == "message" || name == "number" || name == "processing-instruction" || name == "text" || name == "value-of" || name == "variable" ); } return false; } // see: http://www.w3.org/TR/xslt#function-function-available private bool FunctionAvailable(string qname) { string name, prefix; PrefixQName.ParseQualifiedName(qname, out prefix, out name); string ns = LookupNamespace(prefix); if (ns == XmlReservedNs.NsMsxsl) { return name == f_NodeSet; } else if (ns.Length == 0) { return ( // It'll be better to get this information from XPath name == "last" || name == "position" || name == "name" || name == "namespace-uri" || name == "local-name" || name == "count" || name == "id" || name == "string" || name == "concat" || name == "starts-with" || name == "contains" || name == "substring-before" || name == "substring-after" || name == "substring" || name == "string-length" || name == "normalize-space" || name == "translate" || name == "boolean" || name == "not" || name == "true" || name == "false" || name == "lang" || name == "number" || name == "sum" || name == "floor" || name == "ceiling" || name == "round" || // XSLT functions: (s_FunctionTable[name] != null && name != "unparsed-entity-uri") ); } else { // Is this script or extention function? return GetExtentionMethod(ns, name, /*argTypes*/null, out _) != null; } } private XPathNodeIterator Current() { XPathNavigator? nav = _processor!.Current; if (nav != null) { return new XPathSingletonIterator(nav.Clone()); } return XPathEmptyIterator.Instance; } private string SystemProperty(string qname) { string result = string.Empty; string prefix; string local; PrefixQName.ParseQualifiedName(qname, out prefix, out local); // verify the prefix corresponds to the Xslt namespace string urn = LookupNamespace(prefix); if (urn == XmlReservedNs.NsXslt) { if (local == "version") { result = "1"; } else if (local == "vendor") { result = "Microsoft"; } else if (local == "vendor-url") { result = "http://www.microsoft.com"; } } else { if (urn == null && prefix != null) { // if prefix exist it has to be mapped to namespace. // Can it be "" here ? throw XsltException.Create(SR.Xslt_InvalidPrefix, prefix); } return string.Empty; } return result; } public static XPathResultType GetXPathType(Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.String: return XPathResultType.String; case TypeCode.Boolean: return XPathResultType.Boolean; case TypeCode.Object: if (typeof(XPathNavigator).IsAssignableFrom(type) || typeof(IXPathNavigable).IsAssignableFrom(type)) { return XPathResultType.Navigator; } if (typeof(XPathNodeIterator).IsAssignableFrom(type)) { return XPathResultType.NodeSet; } // sdub: It be better to check that type is realy object and otherwise return XPathResultType.Error return XPathResultType.Any; case TypeCode.DateTime: return XPathResultType.Error; default: /* all numeric types */ return XPathResultType.Number; } } // ---------------- Xslt Function Implementations ------------------- // private static Hashtable CreateFunctionTable() { Hashtable ft = new Hashtable(10); { ft["current"] = new FuncCurrent(); ft["unparsed-entity-uri"] = new FuncUnEntityUri(); ft["generate-id"] = new FuncGenerateId(); ft["system-property"] = new FuncSystemProp(); ft["element-available"] = new FuncElementAvailable(); ft["function-available"] = new FuncFunctionAvailable(); ft["document"] = new FuncDocument(); ft["key"] = new FuncKey(); ft["format-number"] = new FuncFormatNumber(); } return ft; } // + IXsltContextFunction // + XsltFunctionImpl func. name, min/max args, return type args types // FuncCurrent "current" 0 0 XPathResultType.NodeSet { } // FuncUnEntityUri "unparsed-entity-uri" 1 1 XPathResultType.String { XPathResultType.String } // FuncGenerateId "generate-id" 0 1 XPathResultType.String { XPathResultType.NodeSet } // FuncSystemProp "system-property" 1 1 XPathResultType.String { XPathResultType.String } // FuncElementAvailable "element-available" 1 1 XPathResultType.Boolean { XPathResultType.String } // FuncFunctionAvailable "function-available" 1 1 XPathResultType.Boolean { XPathResultType.String } // FuncDocument "document" 1 2 XPathResultType.NodeSet { XPathResultType.Any , XPathResultType.NodeSet } // FuncKey "key" 2 2 XPathResultType.NodeSet { XPathResultType.String , XPathResultType.Any } // FuncFormatNumber "format-number" 2 3 XPathResultType.String { XPathResultType.Number , XPathResultType.String, XPathResultType.String } // FuncNodeSet "msxsl:node-set" 1 1 XPathResultType.NodeSet { XPathResultType.Navigator } // FuncExtension // private abstract class XsltFunctionImpl : IXsltContextFunction { private int _minargs; private int _maxargs; private XPathResultType _returnType; private XPathResultType[] _argTypes = null!; // Used by derived classes which initialize it public XsltFunctionImpl() { } public XsltFunctionImpl(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes) { Init(minArgs, maxArgs, returnType, argTypes); } [MemberNotNull(nameof(_argTypes))] protected void Init(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes) { _minargs = minArgs; _maxargs = maxArgs; _returnType = returnType; _argTypes = argTypes; } public int Minargs { get { return _minargs; } } public int Maxargs { get { return _maxargs; } } public XPathResultType ReturnType { get { return _returnType; } } public XPathResultType[] ArgTypes { get { return _argTypes; } } public abstract object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext); // static helper methods: public static XPathNodeIterator ToIterator(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it == null) { throw XsltException.Create(SR.Xslt_NoNodeSetConversion); } return it; } public static XPathNavigator ToNavigator(object argument) { XPathNavigator? nav = argument as XPathNavigator; if (nav == null) { throw XsltException.Create(SR.Xslt_NoNavigatorConversion); } return nav; } private static string IteratorToString(XPathNodeIterator it) { Debug.Assert(it != null); if (it.MoveNext()) { return it.Current!.Value; } return string.Empty; } [return: NotNullIfNotNull("argument")] public static string? ToString(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it != null) { return IteratorToString(it); } else { return XmlConvert.ToXPathString(argument)!; } } public static bool ToBoolean(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it != null) { return Convert.ToBoolean(IteratorToString(it), CultureInfo.InvariantCulture); } XPathNavigator? nav = argument as XPathNavigator; if (nav != null) { return Convert.ToBoolean(nav.ToString(), CultureInfo.InvariantCulture); } return Convert.ToBoolean(argument, CultureInfo.InvariantCulture); } public static double ToNumber(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it != null) { return XmlConvert.ToXPathDouble(IteratorToString(it)); } XPathNavigator? nav = argument as XPathNavigator; if (nav != null) { return XmlConvert.ToXPathDouble(nav.ToString()); } return XmlConvert.ToXPathDouble(argument); } private static object ToNumeric(object argument, Type type) { return Convert.ChangeType(ToNumber(argument), type, CultureInfo.InvariantCulture); } public static object ConvertToXPathType(object val, XPathResultType xt, Type type) { switch (xt) { case XPathResultType.String: // Unfortunetely XPathResultType.String == XPathResultType.Navigator (This is wrong but cant be changed in Everett) // Fortunetely we have typeCode hare so let's discriminate by typeCode if (type == typeof(string)) { return ToString(val); } else { return ToNavigator(val); } case XPathResultType.Number: return ToNumeric(val, type); case XPathResultType.Boolean: return ToBoolean(val); case XPathResultType.NodeSet: return ToIterator(val); // case XPathResultType.Navigator : return ToNavigator(val); case XPathResultType.Any: case XPathResultType.Error: return val; default: Debug.Fail("unexpected XPath type"); return val; } } } private sealed class FuncCurrent : XsltFunctionImpl { public FuncCurrent() : base(0, 0, XPathResultType.NodeSet, Array.Empty<XPathResultType>()) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).Current(); } } private sealed class FuncUnEntityUri : XsltFunctionImpl { public FuncUnEntityUri() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { throw XsltException.Create(SR.Xslt_UnsuppFunction, "unparsed-entity-uri"); } } private sealed class FuncGenerateId : XsltFunctionImpl { public FuncGenerateId() : base(0, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.NodeSet }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { if (args.Length > 0) { XPathNodeIterator it = ToIterator(args[0]); if (it.MoveNext()) { return it.Current!.UniqueId; } else { // if empty nodeset, return empty string, otherwise return generated id return string.Empty; } } else { return docContext.UniqueId; } } } private sealed class FuncSystemProp : XsltFunctionImpl { public FuncSystemProp() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).SystemProperty(ToString(args[0])); } } // see http://www.w3.org/TR/xslt#function-element-available private sealed class FuncElementAvailable : XsltFunctionImpl { public FuncElementAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).ElementAvailable(ToString(args[0])); } } // see: http://www.w3.org/TR/xslt#function-function-available private sealed class FuncFunctionAvailable : XsltFunctionImpl { public FuncFunctionAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).FunctionAvailable(ToString(args[0])); } } private sealed class FuncDocument : XsltFunctionImpl { public FuncDocument() : base(1, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Any, XPathResultType.NodeSet }) { } // SxS: This method uses resource names read from source document and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { string? baseUri = null; if (args.Length == 2) { XPathNodeIterator it = ToIterator(args[1]); if (it.MoveNext()) { baseUri = it.Current!.BaseURI; } else { // http://www.w3.org/1999/11/REC-xslt-19991116-errata (E14): // It is an error if the second argument node-set is empty and the URI reference is relative; the XSLT processor may signal the error; // if it does not signal an error, it must recover by returning an empty node-set. baseUri = string.Empty; // call to Document will fail if args[0] is reletive. } } try { return ((XsltCompileContext)xsltContext).Document(args[0], baseUri); } catch (Exception e) { if (!XmlException.IsCatchableException(e)) { throw; } return XPathEmptyIterator.Instance; } } } private sealed class FuncKey : XsltFunctionImpl { public FuncKey() : base(2, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.String, XPathResultType.Any }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { XsltCompileContext xsltCompileContext = (XsltCompileContext)xsltContext; string local, prefix; PrefixQName.ParseQualifiedName(ToString(args[0]), out prefix, out local); string? ns = xsltContext.LookupNamespace(prefix); XmlQualifiedName keyName = new XmlQualifiedName(local, ns); XPathNavigator root = docContext.Clone(); root.MoveToRoot(); ArrayList? resultCollection = null; foreach (Key key in xsltCompileContext._processor!.KeyList!) { if (key.Name == keyName) { Hashtable? keyTable = key.GetKeys(root); if (keyTable == null) { keyTable = xsltCompileContext.BuildKeyTable(key, root); key.AddKey(root, keyTable); } XPathNodeIterator? it = args[1] as XPathNodeIterator; if (it != null) { it = it.Clone(); while (it.MoveNext()) { resultCollection = AddToList(resultCollection, (ArrayList?)keyTable[it.Current!.Value]); } } else { resultCollection = AddToList(resultCollection, (ArrayList?)keyTable[ToString(args[1])]); } } } if (resultCollection == null) { return XPathEmptyIterator.Instance; } else if (resultCollection[0] is XPathNavigator) { return new XPathArrayIterator(resultCollection); } else { return new XPathMultyIterator(resultCollection); } } private static ArrayList? AddToList(ArrayList? resultCollection, ArrayList? newList) { if (newList == null) { return resultCollection; } if (resultCollection == null) { return newList; } Debug.Assert(resultCollection.Count != 0); Debug.Assert(newList.Count != 0); if (!(resultCollection[0] is ArrayList)) { // Transform resultCollection from ArrayList(XPathNavigator) to ArrayList(ArrayList(XPathNavigator)) Debug.Assert(resultCollection[0] is XPathNavigator); ArrayList firstList = resultCollection; resultCollection = new ArrayList(); resultCollection.Add(firstList); } resultCollection.Add(newList); return resultCollection; } } private sealed class FuncFormatNumber : XsltFunctionImpl { public FuncFormatNumber() : base(2, 3, XPathResultType.String, new XPathResultType[] { XPathResultType.Number, XPathResultType.String, XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { DecimalFormat formatInfo = ((XsltCompileContext)xsltContext).ResolveFormatName(args.Length == 3 ? ToString(args[2]) : null); return DecimalFormatter.Format(ToNumber(args[0]), ToString(args[1]), formatInfo); } } private sealed class FuncNodeSet : XsltFunctionImpl { public FuncNodeSet() : base(1, 1, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Navigator }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return new XPathSingletonIterator(ToNavigator(args[0])); } } private sealed class FuncExtension : XsltFunctionImpl { private readonly object _extension; private readonly MethodInfo _method; private readonly Type[] _types; public FuncExtension(object extension, MethodInfo method) { Debug.Assert(extension != null); Debug.Assert(method != null); _extension = extension; _method = method; XPathResultType returnType = GetXPathType(method.ReturnType); ParameterInfo[] parameters = method.GetParameters(); int minArgs = parameters.Length; int maxArgs = parameters.Length; _types = new Type[parameters.Length]; XPathResultType[] argTypes = new XPathResultType[parameters.Length]; bool optionalParams = true; // we allow only last params be optional. Set false on the first non optional. for (int i = parameters.Length - 1; 0 <= i; i--) { // Revers order is essential: counting optional parameters _types[i] = parameters[i].ParameterType; argTypes[i] = GetXPathType(parameters[i].ParameterType); if (optionalParams) { if (parameters[i].IsOptional) { minArgs--; } else { optionalParams = false; } } } base.Init(minArgs, maxArgs, returnType, argTypes); } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { Debug.Assert(args.Length <= this.Minargs, "We cheking this on resolve time"); for (int i = args.Length - 1; 0 <= i; i--) { args[i] = ConvertToXPathType(args[i], this.ArgTypes[i], _types[i]); } return _method.Invoke(_extension, args)!; } } } }
// 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.Xsl.XsltOld { using System.Diagnostics; using System.IO; using System.Globalization; using System.Collections; using System.Xml.XPath; using System.Xml.Xsl.Runtime; using MS.Internal.Xml.XPath; using System.Reflection; using System.Security; using System.Runtime.Versioning; using System.Diagnostics.CodeAnalysis; internal sealed class XsltCompileContext : XsltContext { private InputScopeManager? _manager; private Processor? _processor; // storage for the functions private static readonly Hashtable s_FunctionTable = CreateFunctionTable(); private static readonly IXsltContextFunction s_FuncNodeSet = new FuncNodeSet(); private const string f_NodeSet = "node-set"; internal XsltCompileContext(InputScopeManager manager, Processor processor) : base(/*dummy*/false) { _manager = manager; _processor = processor; } internal XsltCompileContext() : base(/*dummy*/ false) { } internal void Recycle() { _manager = null; _processor = null; } internal void Reinitialize(InputScopeManager manager, Processor processor) { _manager = manager; _processor = processor; } public override int CompareDocument(string baseUri, string nextbaseUri) { return string.Compare(baseUri, nextbaseUri, StringComparison.Ordinal); } // Namespace support public override string DefaultNamespace { get { return string.Empty; } } public override string LookupNamespace(string prefix) { return _manager!.ResolveXPathNamespace(prefix); } // --------------------------- XsltContext ------------------- // Resolving variables and functions public override IXsltContextVariable ResolveVariable(string prefix, string name) { string namespaceURI = this.LookupNamespace(prefix); XmlQualifiedName qname = new XmlQualifiedName(name, namespaceURI); IXsltContextVariable? variable = _manager!.VariableScope.ResolveVariable(qname); if (variable == null) { throw XsltException.Create(SR.Xslt_InvalidVariable, qname.ToString()); } return variable; } internal object EvaluateVariable(VariableAction variable) { object result = _processor!.GetVariableValue(variable); if (result == null && !variable.IsGlobal) { // This was uninitialized local variable. May be we have sutable global var too? VariableAction? global = _manager!.VariableScope.ResolveGlobalVariable(variable.Name!); if (global != null) { result = _processor.GetVariableValue(global); } } if (result == null) { throw XsltException.Create(SR.Xslt_InvalidVariable, variable.Name!.ToString()); } return result; } // Whitespace stripping support public override bool Whitespace { get { return _processor!.Stylesheet.Whitespace; } } public override bool PreserveWhitespace(XPathNavigator node) { node = node.Clone(); node.MoveToParent(); return _processor!.Stylesheet.PreserveWhiteSpace(_processor, node); } private MethodInfo? FindBestMethod(MethodInfo[] methods, bool ignoreCase, bool publicOnly, string name, XPathResultType[]? argTypes) { int length = methods.Length; int free = 0; // restrict search to methods with the same name and requiested protection attribute for (int i = 0; i < length; i++) { if (string.Equals(name, methods[i].Name, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { if (!publicOnly || methods[i].GetBaseDefinition().IsPublic) { methods[free++] = methods[i]; } } } length = free; if (length == 0) { // this is the only place we returning null in this function return null; } if (argTypes == null) { // without arg types we can't do more detailed search return methods[0]; } // restrict search by number of parameters free = 0; for (int i = 0; i < length; i++) { if (methods[i].GetParameters().Length == argTypes.Length) { methods[free++] = methods[i]; } } length = free; if (length <= 1) { // 0 -- not method found. We have to return non-null and let it fail with correct exception on call. // 1 -- no reason to continue search anyway. return methods[0]; } // restrict search by parameters type free = 0; for (int i = 0; i < length; i++) { bool match = true; ParameterInfo[] parameters = methods[i].GetParameters(); for (int par = 0; par < parameters.Length; par++) { XPathResultType required = argTypes[par]; if (required == XPathResultType.Any) { continue; // Any means we don't know type and can't discriminate by it } XPathResultType actual = GetXPathType(parameters[par].ParameterType); if ( actual != required && actual != XPathResultType.Any // actual arg is object and we can pass everithing here. ) { match = false; break; } } if (match) { methods[free++] = methods[i]; } } return methods[0]; } private const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:RequiresUnreferencedCode", Justification = XsltArgumentList.ExtensionObjectSuppresion)] private IXsltContextFunction? GetExtentionMethod(string ns, string name, XPathResultType[]? argTypes, out object? extension) { FuncExtension? result = null; extension = _processor!.GetScriptObject(ns); if (extension != null) { MethodInfo? method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/true, /*publicOnly:*/false, name, argTypes); if (method != null) { result = new FuncExtension(extension, method); } return result; } extension = _processor.GetExtensionObject(ns); if (extension != null) { MethodInfo? method = FindBestMethod(extension.GetType().GetMethods(bindingFlags), /*ignoreCase:*/false, /*publicOnly:*/true, name, argTypes); if (method != null) { result = new FuncExtension(extension, method); } return result; } return null; } public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] argTypes) { IXsltContextFunction? func; if (prefix.Length == 0) { func = s_FunctionTable[name] as IXsltContextFunction; } else { string ns = this.LookupNamespace(prefix); if (ns == XmlReservedNs.NsMsxsl && name == f_NodeSet) { func = s_FuncNodeSet; } else { object? extension; func = GetExtentionMethod(ns, name, argTypes, out extension); if (extension == null) { throw XsltException.Create(SR.Xslt_ScriptInvalidPrefix, prefix); // BugBug: It's better to say that method 'name' not found } } } if (func == null) { throw XsltException.Create(SR.Xslt_UnknownXsltFunction, name); } if (argTypes.Length < func.Minargs || func.Maxargs < argTypes.Length) { throw XsltException.Create(SR.Xslt_WrongNumberArgs, name, argTypes.Length.ToString(CultureInfo.InvariantCulture)); } return func; } // // Xslt Function Extensions to XPath // private Uri ComposeUri(string thisUri, string baseUri) { Debug.Assert(thisUri != null && baseUri != null); XmlResolver resolver = _processor!.Resolver; Uri? uriBase = null; if (baseUri.Length != 0) { uriBase = resolver.ResolveUri(null, baseUri); } return resolver.ResolveUri(uriBase, thisUri); } private XPathNodeIterator Document(object arg0, string? baseUri) { XPathNodeIterator? it = arg0 as XPathNodeIterator; if (it != null) { ArrayList list = new ArrayList(); Hashtable documents = new Hashtable(); while (it.MoveNext()) { Uri uri = ComposeUri(it.Current!.Value, baseUri ?? it.Current.BaseURI); if (!documents.ContainsKey(uri)) { documents.Add(uri, null); list.Add(_processor!.GetNavigator(uri)); } } return new XPathArrayIterator(list); } else { return new XPathSingletonIterator( _processor!.GetNavigator( ComposeUri(XmlConvert.ToXPathString(arg0)!, baseUri ?? _manager!.Navigator.BaseURI) ) ); } } private Hashtable BuildKeyTable(Key key, XPathNavigator root) { Hashtable keyTable = new Hashtable(); string matchStr = _processor!.GetQueryExpression(key.MatchKey); Query matchExpr = _processor.GetCompiledQuery(key.MatchKey); Query useExpr = _processor.GetCompiledQuery(key.UseKey); XPathNodeIterator sel = root.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ false); while (sel.MoveNext()) { XPathNavigator node = sel.Current!; EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable); if (node.MoveToFirstAttribute()) { do { EvaluateKey(node, matchExpr, matchStr, useExpr, keyTable); } while (node.MoveToNextAttribute()); node.MoveToParent(); } } return keyTable; } private static void AddKeyValue(Hashtable keyTable, string key, XPathNavigator value, bool checkDuplicates) { ArrayList? list = (ArrayList?)keyTable[key]; if (list == null) { list = new ArrayList(); keyTable.Add(key, list); } else { Debug.Assert( value.ComparePosition((XPathNavigator?)list[list.Count - 1]) != XmlNodeOrder.Before, "The way we traversing nodes should garantees node-order" ); if (checkDuplicates) { // it's posible that this value already was assosiated with current node // but if this happened the node is last in the list of values. if (value.ComparePosition((XPathNavigator?)list[list.Count - 1]) == XmlNodeOrder.Same) { return; } } else { Debug.Assert( value.ComparePosition((XPathNavigator?)list[list.Count - 1]) != XmlNodeOrder.Same, "checkDuplicates == false : We can't have duplicates" ); } } list.Add(value.Clone()); } private static void EvaluateKey(XPathNavigator? node, Query matchExpr, string matchStr, Query useExpr, Hashtable keyTable) { try { if (matchExpr.MatchNode(node) == null) { return; } } catch (XPathException) { throw XsltException.Create(SR.Xslt_InvalidPattern, matchStr); } object result = useExpr.Evaluate(new XPathSingletonIterator(node!, /*moved:*/true)); XPathNodeIterator? it = result as XPathNodeIterator; if (it != null) { bool checkDuplicates = false; while (it.MoveNext()) { AddKeyValue(keyTable, /*key:*/it.Current!.Value!, /*value:*/node!, checkDuplicates); checkDuplicates = true; } } else { string key = XmlConvert.ToXPathString(result)!; AddKeyValue(keyTable, key, /*value:*/node!, /*checkDuplicates:*/ false); } } private DecimalFormat ResolveFormatName(string? formatName) { string ns = string.Empty, local = string.Empty; if (formatName != null) { string prefix; PrefixQName.ParseQualifiedName(formatName, out prefix, out local); ns = LookupNamespace(prefix); } DecimalFormat? formatInfo = _processor!.RootAction!.GetDecimalFormat(new XmlQualifiedName(local, ns)); if (formatInfo == null) { if (formatName != null) { throw XsltException.Create(SR.Xslt_NoDecimalFormat, formatName); } formatInfo = new DecimalFormat(new NumberFormatInfo(), '#', '0', ';'); } return formatInfo; } // see http://www.w3.org/TR/xslt#function-element-available private bool ElementAvailable(string qname) { string name, prefix; PrefixQName.ParseQualifiedName(qname, out prefix, out name); string ns = _manager!.ResolveXmlNamespace(prefix); // msxsl:script - is not an "instruction" so we return false for it. if (ns == XmlReservedNs.NsXslt) { return ( name == "apply-imports" || name == "apply-templates" || name == "attribute" || name == "call-template" || name == "choose" || name == "comment" || name == "copy" || name == "copy-of" || name == "element" || name == "fallback" || name == "for-each" || name == "if" || name == "message" || name == "number" || name == "processing-instruction" || name == "text" || name == "value-of" || name == "variable" ); } return false; } // see: http://www.w3.org/TR/xslt#function-function-available private bool FunctionAvailable(string qname) { string name, prefix; PrefixQName.ParseQualifiedName(qname, out prefix, out name); string ns = LookupNamespace(prefix); if (ns == XmlReservedNs.NsMsxsl) { return name == f_NodeSet; } else if (ns.Length == 0) { return ( // It'll be better to get this information from XPath name == "last" || name == "position" || name == "name" || name == "namespace-uri" || name == "local-name" || name == "count" || name == "id" || name == "string" || name == "concat" || name == "starts-with" || name == "contains" || name == "substring-before" || name == "substring-after" || name == "substring" || name == "string-length" || name == "normalize-space" || name == "translate" || name == "boolean" || name == "not" || name == "true" || name == "false" || name == "lang" || name == "number" || name == "sum" || name == "floor" || name == "ceiling" || name == "round" || // XSLT functions: (s_FunctionTable[name] != null && name != "unparsed-entity-uri") ); } else { // Is this script or extention function? return GetExtentionMethod(ns, name, /*argTypes*/null, out _) != null; } } private XPathNodeIterator Current() { XPathNavigator? nav = _processor!.Current; if (nav != null) { return new XPathSingletonIterator(nav.Clone()); } return XPathEmptyIterator.Instance; } private string SystemProperty(string qname) { string result = string.Empty; string prefix; string local; PrefixQName.ParseQualifiedName(qname, out prefix, out local); // verify the prefix corresponds to the Xslt namespace string urn = LookupNamespace(prefix); if (urn == XmlReservedNs.NsXslt) { if (local == "version") { result = "1"; } else if (local == "vendor") { result = "Microsoft"; } else if (local == "vendor-url") { result = "http://www.microsoft.com"; } } else { if (urn == null && prefix != null) { // if prefix exist it has to be mapped to namespace. // Can it be "" here ? throw XsltException.Create(SR.Xslt_InvalidPrefix, prefix); } return string.Empty; } return result; } public static XPathResultType GetXPathType(Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.String: return XPathResultType.String; case TypeCode.Boolean: return XPathResultType.Boolean; case TypeCode.Object: if (typeof(XPathNavigator).IsAssignableFrom(type) || typeof(IXPathNavigable).IsAssignableFrom(type)) { return XPathResultType.Navigator; } if (typeof(XPathNodeIterator).IsAssignableFrom(type)) { return XPathResultType.NodeSet; } // sdub: It be better to check that type is realy object and otherwise return XPathResultType.Error return XPathResultType.Any; case TypeCode.DateTime: return XPathResultType.Error; default: /* all numeric types */ return XPathResultType.Number; } } // ---------------- Xslt Function Implementations ------------------- // private static Hashtable CreateFunctionTable() { Hashtable ft = new Hashtable(10); { ft["current"] = new FuncCurrent(); ft["unparsed-entity-uri"] = new FuncUnEntityUri(); ft["generate-id"] = new FuncGenerateId(); ft["system-property"] = new FuncSystemProp(); ft["element-available"] = new FuncElementAvailable(); ft["function-available"] = new FuncFunctionAvailable(); ft["document"] = new FuncDocument(); ft["key"] = new FuncKey(); ft["format-number"] = new FuncFormatNumber(); } return ft; } // + IXsltContextFunction // + XsltFunctionImpl func. name, min/max args, return type args types // FuncCurrent "current" 0 0 XPathResultType.NodeSet { } // FuncUnEntityUri "unparsed-entity-uri" 1 1 XPathResultType.String { XPathResultType.String } // FuncGenerateId "generate-id" 0 1 XPathResultType.String { XPathResultType.NodeSet } // FuncSystemProp "system-property" 1 1 XPathResultType.String { XPathResultType.String } // FuncElementAvailable "element-available" 1 1 XPathResultType.Boolean { XPathResultType.String } // FuncFunctionAvailable "function-available" 1 1 XPathResultType.Boolean { XPathResultType.String } // FuncDocument "document" 1 2 XPathResultType.NodeSet { XPathResultType.Any , XPathResultType.NodeSet } // FuncKey "key" 2 2 XPathResultType.NodeSet { XPathResultType.String , XPathResultType.Any } // FuncFormatNumber "format-number" 2 3 XPathResultType.String { XPathResultType.Number , XPathResultType.String, XPathResultType.String } // FuncNodeSet "msxsl:node-set" 1 1 XPathResultType.NodeSet { XPathResultType.Navigator } // FuncExtension // private abstract class XsltFunctionImpl : IXsltContextFunction { private int _minargs; private int _maxargs; private XPathResultType _returnType; private XPathResultType[] _argTypes = null!; // Used by derived classes which initialize it public XsltFunctionImpl() { } public XsltFunctionImpl(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes) { Init(minArgs, maxArgs, returnType, argTypes); } [MemberNotNull(nameof(_argTypes))] protected void Init(int minArgs, int maxArgs, XPathResultType returnType, XPathResultType[] argTypes) { _minargs = minArgs; _maxargs = maxArgs; _returnType = returnType; _argTypes = argTypes; } public int Minargs { get { return _minargs; } } public int Maxargs { get { return _maxargs; } } public XPathResultType ReturnType { get { return _returnType; } } public XPathResultType[] ArgTypes { get { return _argTypes; } } public abstract object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext); // static helper methods: public static XPathNodeIterator ToIterator(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it == null) { throw XsltException.Create(SR.Xslt_NoNodeSetConversion); } return it; } public static XPathNavigator ToNavigator(object argument) { XPathNavigator? nav = argument as XPathNavigator; if (nav == null) { throw XsltException.Create(SR.Xslt_NoNavigatorConversion); } return nav; } private static string IteratorToString(XPathNodeIterator it) { Debug.Assert(it != null); if (it.MoveNext()) { return it.Current!.Value; } return string.Empty; } [return: NotNullIfNotNull("argument")] public static string? ToString(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it != null) { return IteratorToString(it); } else { return XmlConvert.ToXPathString(argument)!; } } public static bool ToBoolean(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it != null) { return Convert.ToBoolean(IteratorToString(it), CultureInfo.InvariantCulture); } XPathNavigator? nav = argument as XPathNavigator; if (nav != null) { return Convert.ToBoolean(nav.ToString(), CultureInfo.InvariantCulture); } return Convert.ToBoolean(argument, CultureInfo.InvariantCulture); } public static double ToNumber(object argument) { XPathNodeIterator? it = argument as XPathNodeIterator; if (it != null) { return XmlConvert.ToXPathDouble(IteratorToString(it)); } XPathNavigator? nav = argument as XPathNavigator; if (nav != null) { return XmlConvert.ToXPathDouble(nav.ToString()); } return XmlConvert.ToXPathDouble(argument); } private static object ToNumeric(object argument, Type type) { return Convert.ChangeType(ToNumber(argument), type, CultureInfo.InvariantCulture); } public static object ConvertToXPathType(object val, XPathResultType xt, Type type) { switch (xt) { case XPathResultType.String: // Unfortunetely XPathResultType.String == XPathResultType.Navigator (This is wrong but cant be changed in Everett) // Fortunetely we have typeCode hare so let's discriminate by typeCode if (type == typeof(string)) { return ToString(val); } else { return ToNavigator(val); } case XPathResultType.Number: return ToNumeric(val, type); case XPathResultType.Boolean: return ToBoolean(val); case XPathResultType.NodeSet: return ToIterator(val); // case XPathResultType.Navigator : return ToNavigator(val); case XPathResultType.Any: case XPathResultType.Error: return val; default: Debug.Fail("unexpected XPath type"); return val; } } } private sealed class FuncCurrent : XsltFunctionImpl { public FuncCurrent() : base(0, 0, XPathResultType.NodeSet, Array.Empty<XPathResultType>()) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).Current(); } } private sealed class FuncUnEntityUri : XsltFunctionImpl { public FuncUnEntityUri() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { throw XsltException.Create(SR.Xslt_UnsuppFunction, "unparsed-entity-uri"); } } private sealed class FuncGenerateId : XsltFunctionImpl { public FuncGenerateId() : base(0, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.NodeSet }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { if (args.Length > 0) { XPathNodeIterator it = ToIterator(args[0]); if (it.MoveNext()) { return it.Current!.UniqueId; } else { // if empty nodeset, return empty string, otherwise return generated id return string.Empty; } } else { return docContext.UniqueId; } } } private sealed class FuncSystemProp : XsltFunctionImpl { public FuncSystemProp() : base(1, 1, XPathResultType.String, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).SystemProperty(ToString(args[0])); } } // see http://www.w3.org/TR/xslt#function-element-available private sealed class FuncElementAvailable : XsltFunctionImpl { public FuncElementAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).ElementAvailable(ToString(args[0])); } } // see: http://www.w3.org/TR/xslt#function-function-available private sealed class FuncFunctionAvailable : XsltFunctionImpl { public FuncFunctionAvailable() : base(1, 1, XPathResultType.Boolean, new XPathResultType[] { XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return ((XsltCompileContext)xsltContext).FunctionAvailable(ToString(args[0])); } } private sealed class FuncDocument : XsltFunctionImpl { public FuncDocument() : base(1, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Any, XPathResultType.NodeSet }) { } // SxS: This method uses resource names read from source document and does not expose any resources to the caller. // It's OK to suppress the SxS warning. public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { string? baseUri = null; if (args.Length == 2) { XPathNodeIterator it = ToIterator(args[1]); if (it.MoveNext()) { baseUri = it.Current!.BaseURI; } else { // http://www.w3.org/1999/11/REC-xslt-19991116-errata (E14): // It is an error if the second argument node-set is empty and the URI reference is relative; the XSLT processor may signal the error; // if it does not signal an error, it must recover by returning an empty node-set. baseUri = string.Empty; // call to Document will fail if args[0] is reletive. } } try { return ((XsltCompileContext)xsltContext).Document(args[0], baseUri); } catch (Exception e) { if (!XmlException.IsCatchableException(e)) { throw; } return XPathEmptyIterator.Instance; } } } private sealed class FuncKey : XsltFunctionImpl { public FuncKey() : base(2, 2, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.String, XPathResultType.Any }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { XsltCompileContext xsltCompileContext = (XsltCompileContext)xsltContext; string local, prefix; PrefixQName.ParseQualifiedName(ToString(args[0]), out prefix, out local); string? ns = xsltContext.LookupNamespace(prefix); XmlQualifiedName keyName = new XmlQualifiedName(local, ns); XPathNavigator root = docContext.Clone(); root.MoveToRoot(); ArrayList? resultCollection = null; foreach (Key key in xsltCompileContext._processor!.KeyList!) { if (key.Name == keyName) { Hashtable? keyTable = key.GetKeys(root); if (keyTable == null) { keyTable = xsltCompileContext.BuildKeyTable(key, root); key.AddKey(root, keyTable); } XPathNodeIterator? it = args[1] as XPathNodeIterator; if (it != null) { it = it.Clone(); while (it.MoveNext()) { resultCollection = AddToList(resultCollection, (ArrayList?)keyTable[it.Current!.Value]); } } else { resultCollection = AddToList(resultCollection, (ArrayList?)keyTable[ToString(args[1])]); } } } if (resultCollection == null) { return XPathEmptyIterator.Instance; } else if (resultCollection[0] is XPathNavigator) { return new XPathArrayIterator(resultCollection); } else { return new XPathMultyIterator(resultCollection); } } private static ArrayList? AddToList(ArrayList? resultCollection, ArrayList? newList) { if (newList == null) { return resultCollection; } if (resultCollection == null) { return newList; } Debug.Assert(resultCollection.Count != 0); Debug.Assert(newList.Count != 0); if (!(resultCollection[0] is ArrayList)) { // Transform resultCollection from ArrayList(XPathNavigator) to ArrayList(ArrayList(XPathNavigator)) Debug.Assert(resultCollection[0] is XPathNavigator); ArrayList firstList = resultCollection; resultCollection = new ArrayList(); resultCollection.Add(firstList); } resultCollection.Add(newList); return resultCollection; } } private sealed class FuncFormatNumber : XsltFunctionImpl { public FuncFormatNumber() : base(2, 3, XPathResultType.String, new XPathResultType[] { XPathResultType.Number, XPathResultType.String, XPathResultType.String }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { DecimalFormat formatInfo = ((XsltCompileContext)xsltContext).ResolveFormatName(args.Length == 3 ? ToString(args[2]) : null); return DecimalFormatter.Format(ToNumber(args[0]), ToString(args[1]), formatInfo); } } private sealed class FuncNodeSet : XsltFunctionImpl { public FuncNodeSet() : base(1, 1, XPathResultType.NodeSet, new XPathResultType[] { XPathResultType.Navigator }) { } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { return new XPathSingletonIterator(ToNavigator(args[0])); } } private sealed class FuncExtension : XsltFunctionImpl { private readonly object _extension; private readonly MethodInfo _method; private readonly Type[] _types; public FuncExtension(object extension, MethodInfo method) { Debug.Assert(extension != null); Debug.Assert(method != null); _extension = extension; _method = method; XPathResultType returnType = GetXPathType(method.ReturnType); ParameterInfo[] parameters = method.GetParameters(); int minArgs = parameters.Length; int maxArgs = parameters.Length; _types = new Type[parameters.Length]; XPathResultType[] argTypes = new XPathResultType[parameters.Length]; bool optionalParams = true; // we allow only last params be optional. Set false on the first non optional. for (int i = parameters.Length - 1; 0 <= i; i--) { // Revers order is essential: counting optional parameters _types[i] = parameters[i].ParameterType; argTypes[i] = GetXPathType(parameters[i].ParameterType); if (optionalParams) { if (parameters[i].IsOptional) { minArgs--; } else { optionalParams = false; } } } base.Init(minArgs, maxArgs, returnType, argTypes); } public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext) { Debug.Assert(args.Length <= this.Minargs, "We cheking this on resolve time"); for (int i = args.Length - 1; 0 <= i; i--) { args[i] = ConvertToXPathType(args[i], this.ArgTypes[i], _types[i]); } return _method.Invoke(_extension, args)!; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Errors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.CSharp.RuntimeBinder.ComInterop { /// <summary> /// Strongly-typed and parameterized exception factory. /// </summary> internal static partial class Error { /// <summary> /// InvalidOperationException with message like "Marshal.SetComObjectData failed." /// </summary> internal static Exception SetComObjectDataFailed() { return new InvalidOperationException(SR.COMSetComObjectDataFailed); } /// <summary> /// InvalidOperationException with message like "Unexpected VarEnum {0}." /// </summary> internal static Exception UnexpectedVarEnum(object p0) { return new InvalidOperationException(SR.Format(SR.COMUnexpectedVarEnum, p0)); } /// <summary> /// System.Reflection.TargetParameterCountException with message like "Error while invoking {0}." /// </summary> internal static Exception DispBadParamCount(object p0) { return new System.Reflection.TargetParameterCountException(SR.Format(SR.COMDispatchInvokeError, p0)); } /// <summary> /// MissingMemberException with message like "Error while invoking {0}." /// </summary> internal static Exception DispMemberNotFound(object p0) { return new MissingMemberException(SR.Format(SR.COMDispatchInvokeError, p0)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. Named arguments are not supported." /// </summary> internal static Exception DispNoNamedArgs(object p0) { return new ArgumentException(SR.Format(SR.COMDispatchInvokeErrorNoNamedArgs, p0)); } /// <summary> /// OverflowException with message like "Error while invoking {0}." /// </summary> internal static Exception DispOverflow(object p0) { return new OverflowException(SR.Format(SR.COMDispatchInvokeError, p0)); } /// <summary> /// ArgumentException with message like "Could not convert argument {0} for call to {1}." /// </summary> internal static Exception DispTypeMismatch(object p0, object p1) { return new ArgumentException(SR.Format(SR.COMDispatchInvokeErrorTypeMismatch, p0, p1)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. A required parameter was omitted." /// </summary> internal static Exception DispParamNotOptional(object p0) { return new ArgumentException(SR.Format(SR.COMDispatchInvokeErrorParamNotOptional, p0)); } /// <summary> /// InvalidOperationException with message like "Cannot retrieve type information." /// </summary> internal static Exception CannotRetrieveTypeInformation() { return new InvalidOperationException(SR.COMCannotRetrieveTypeInfo); } /// <summary> /// ArgumentException with message like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." /// </summary> internal static Exception GetIDsOfNamesInvalid(object p0) { return new ArgumentException(SR.Format(SR.COMGetIDsOfNamesInvalid, p0)); } /// <summary> /// InvalidOperationException with message like "Attempting to pass an event handler of an unsupported type." /// </summary> internal static Exception UnsupportedHandlerType() { return new InvalidOperationException(SR.COMUnsupportedEventHandlerType); } /// <summary> /// MissingMemberException with message like "Could not get dispatch ID for {0} (error: {1})." /// </summary> internal static Exception CouldNotGetDispId(object p0, object p1) { return new MissingMemberException(SR.Format(SR.COMGetDispatchIdFailed, p0, p1)); } /// <summary> /// System.Reflection.AmbiguousMatchException with message like "There are valid conversions from {0} to {1}." /// </summary> internal static Exception AmbiguousConversion(object p0, object p1) { return new System.Reflection.AmbiguousMatchException(SR.Format(SR.COMAmbiguousConversion, p0, p1)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.CSharp.RuntimeBinder.ComInterop { /// <summary> /// Strongly-typed and parameterized exception factory. /// </summary> internal static partial class Error { /// <summary> /// InvalidOperationException with message like "Marshal.SetComObjectData failed." /// </summary> internal static Exception SetComObjectDataFailed() { return new InvalidOperationException(SR.COMSetComObjectDataFailed); } /// <summary> /// InvalidOperationException with message like "Unexpected VarEnum {0}." /// </summary> internal static Exception UnexpectedVarEnum(object p0) { return new InvalidOperationException(SR.Format(SR.COMUnexpectedVarEnum, p0)); } /// <summary> /// System.Reflection.TargetParameterCountException with message like "Error while invoking {0}." /// </summary> internal static Exception DispBadParamCount(object p0) { return new System.Reflection.TargetParameterCountException(SR.Format(SR.COMDispatchInvokeError, p0)); } /// <summary> /// MissingMemberException with message like "Error while invoking {0}." /// </summary> internal static Exception DispMemberNotFound(object p0) { return new MissingMemberException(SR.Format(SR.COMDispatchInvokeError, p0)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. Named arguments are not supported." /// </summary> internal static Exception DispNoNamedArgs(object p0) { return new ArgumentException(SR.Format(SR.COMDispatchInvokeErrorNoNamedArgs, p0)); } /// <summary> /// OverflowException with message like "Error while invoking {0}." /// </summary> internal static Exception DispOverflow(object p0) { return new OverflowException(SR.Format(SR.COMDispatchInvokeError, p0)); } /// <summary> /// ArgumentException with message like "Could not convert argument {0} for call to {1}." /// </summary> internal static Exception DispTypeMismatch(object p0, object p1) { return new ArgumentException(SR.Format(SR.COMDispatchInvokeErrorTypeMismatch, p0, p1)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. A required parameter was omitted." /// </summary> internal static Exception DispParamNotOptional(object p0) { return new ArgumentException(SR.Format(SR.COMDispatchInvokeErrorParamNotOptional, p0)); } /// <summary> /// InvalidOperationException with message like "Cannot retrieve type information." /// </summary> internal static Exception CannotRetrieveTypeInformation() { return new InvalidOperationException(SR.COMCannotRetrieveTypeInfo); } /// <summary> /// ArgumentException with message like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." /// </summary> internal static Exception GetIDsOfNamesInvalid(object p0) { return new ArgumentException(SR.Format(SR.COMGetIDsOfNamesInvalid, p0)); } /// <summary> /// InvalidOperationException with message like "Attempting to pass an event handler of an unsupported type." /// </summary> internal static Exception UnsupportedHandlerType() { return new InvalidOperationException(SR.COMUnsupportedEventHandlerType); } /// <summary> /// MissingMemberException with message like "Could not get dispatch ID for {0} (error: {1})." /// </summary> internal static Exception CouldNotGetDispId(object p0, object p1) { return new MissingMemberException(SR.Format(SR.COMGetDispatchIdFailed, p0, p1)); } /// <summary> /// System.Reflection.AmbiguousMatchException with message like "There are valid conversions from {0} to {1}." /// </summary> internal static Exception AmbiguousConversion(object p0, object p1) { return new System.Reflection.AmbiguousMatchException(SR.Format(SR.COMAmbiguousConversion, p0, p1)); } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/mono/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.Mono.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.Diagnostics.Tracing { internal static partial class EventPipeInternal { #if FEATURE_PERFTRACING // These ICalls are used by the configuration APIs to interact with EventPipe. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern unsafe ulong Enable(char* outputFile, EventPipeSerializationFormat format, uint circularBufferSizeInMB, EventPipeProviderConfigurationNative* providers, uint numProviders); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void Disable(ulong sessionID); // // These ICalls are used by EventSource to interact with the EventPipe. // [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr CreateProvider(string providerName, Interop.Advapi32.EtwEnableCallback callbackFunc); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr DefineEvent(IntPtr provHandle, uint eventID, long keywords, uint eventVersion, uint level, byte* pMetadata, uint metadataLength); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr GetProvider(char* providerName); internal static unsafe IntPtr GetProvider(string providerName) { fixed (char* p = providerName) { return GetProvider(p); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void DeleteProvider(IntPtr provHandle); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int EventActivityIdControl(uint controlCode, ref Guid activityId); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe void WriteEventData(IntPtr eventHandle, EventProvider.EventData* pEventData, uint dataCount, Guid* activityId, Guid* relatedActivityId); // // These ICalls are used as part of the EventPipeEventDispatcher. // [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe bool GetSessionInfo(ulong sessionID, EventPipeSessionInfo* pSessionInfo); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe bool GetNextEvent(ulong sessionID, EventPipeEventInstanceData* pInstance); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr GetWaitHandle(ulong sessionID); #endif // FEATURE_PERFTRACING // // This ICall are used as part of getting runtime implemented counter values. // // // NOTE, keep in sync with icall-eventpipe.c, EventPipeRuntimeCounters. // internal enum RuntimeCounters { ASSEMBLY_COUNT, EXCEPTION_COUNT, GC_NURSERY_SIZE_BYTES, GC_MAJOR_SIZE_BYTES, GC_LARGE_OBJECT_SIZE_BYTES, GC_LAST_PERCENT_TIME_IN_GC, JIT_IL_BYTES_JITTED, JIT_METHODS_JITTED, JIT_TICKS_IN_JIT } #if FEATURE_PERFTRACING [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern ulong GetRuntimeCounterValue(RuntimeCounters counterID); #else internal static ulong GetRuntimeCounterValue(RuntimeCounters counterID) { return 0; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Diagnostics.Tracing { internal static partial class EventPipeInternal { #if FEATURE_PERFTRACING // These ICalls are used by the configuration APIs to interact with EventPipe. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern unsafe ulong Enable(char* outputFile, EventPipeSerializationFormat format, uint circularBufferSizeInMB, EventPipeProviderConfigurationNative* providers, uint numProviders); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void Disable(ulong sessionID); // // These ICalls are used by EventSource to interact with the EventPipe. // [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr CreateProvider(string providerName, Interop.Advapi32.EtwEnableCallback callbackFunc); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr DefineEvent(IntPtr provHandle, uint eventID, long keywords, uint eventVersion, uint level, byte* pMetadata, uint metadataLength); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr GetProvider(char* providerName); internal static unsafe IntPtr GetProvider(string providerName) { fixed (char* p = providerName) { return GetProvider(p); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void DeleteProvider(IntPtr provHandle); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int EventActivityIdControl(uint controlCode, ref Guid activityId); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe void WriteEventData(IntPtr eventHandle, EventProvider.EventData* pEventData, uint dataCount, Guid* activityId, Guid* relatedActivityId); // // These ICalls are used as part of the EventPipeEventDispatcher. // [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe bool GetSessionInfo(ulong sessionID, EventPipeSessionInfo* pSessionInfo); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe bool GetNextEvent(ulong sessionID, EventPipeEventInstanceData* pInstance); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr GetWaitHandle(ulong sessionID); #endif // FEATURE_PERFTRACING // // This ICall are used as part of getting runtime implemented counter values. // // // NOTE, keep in sync with icall-eventpipe.c, EventPipeRuntimeCounters. // internal enum RuntimeCounters { ASSEMBLY_COUNT, EXCEPTION_COUNT, GC_NURSERY_SIZE_BYTES, GC_MAJOR_SIZE_BYTES, GC_LARGE_OBJECT_SIZE_BYTES, GC_LAST_PERCENT_TIME_IN_GC, JIT_IL_BYTES_JITTED, JIT_METHODS_JITTED, JIT_TICKS_IN_JIT } #if FEATURE_PERFTRACING [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern ulong GetRuntimeCounterValue(RuntimeCounters counterID); #else internal static ulong GetRuntimeCounterValue(RuntimeCounters counterID) { return 0; } #endif } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/opt/Devirtualization/sealedmethod.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 Base { public virtual int GetValue(int value) { return 0x33; } } public class Derived : Base { public sealed override int GetValue(int value) { return value; } } public class F { [MethodImpl(MethodImplOptions.NoInlining)] public static int TestSealedMethodInlining(Derived obj) { return obj.GetValue(3); } public static int Main(string[] args) { Derived d = new Derived(); int v = TestSealedMethodInlining(d); return (v == 3 ? 100 : -1); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; public class Base { public virtual int GetValue(int value) { return 0x33; } } public class Derived : Base { public sealed override int GetValue(int value) { return value; } } public class F { [MethodImpl(MethodImplOptions.NoInlining)] public static int TestSealedMethodInlining(Derived obj) { return obj.GetValue(3); } public static int Main(string[] args) { Derived d = new Derived(); int v = TestSealedMethodInlining(d); return (v == 3 ? 100 : -1); } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Threading.Thread/tests/ExceptionTests.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.Threading.Threads.Tests { public static class ExceptionTests { private const int ThreadInterruptedException_HResult = unchecked((int)0x80131519); private const int ThreadStateException_HResult = unchecked((int)0x80131520); private static void ConstructorTest<T>( int expectedHResult, Func<T> createDefault, Func<string, T> createWithMessage, Func<string, Exception, T> createWithMessageAndException) where T : Exception { var ex = createDefault(); Assert.False(string.IsNullOrEmpty(ex.Message)); Assert.Null(ex.InnerException); Assert.Equal(expectedHResult, ex.HResult); var message = "foo"; ex = createWithMessage(message); Assert.Equal(message, ex.Message); Assert.Null(ex.InnerException); Assert.Equal(expectedHResult, ex.HResult); var innerException = new Exception(); ex = createWithMessageAndException(message, innerException); Assert.Equal(message, ex.Message); Assert.Equal(innerException, ex.InnerException); Assert.Equal(expectedHResult, ex.HResult); } [Fact] public static void ThreadInterruptedException_ConstructorTest() { ConstructorTest<ThreadInterruptedException>( ThreadInterruptedException_HResult, () => new ThreadInterruptedException(), message => new ThreadInterruptedException(message), (message, innerException) => new ThreadInterruptedException(message, innerException)); } [Fact] public static void ThreadStateException_ConstructorTest() { ConstructorTest<ThreadStateException>( ThreadStateException_HResult, () => new ThreadStateException(), message => new ThreadStateException(message), (message, innerException) => new ThreadStateException(message, innerException)); } } }
// 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.Threading.Threads.Tests { public static class ExceptionTests { private const int ThreadInterruptedException_HResult = unchecked((int)0x80131519); private const int ThreadStateException_HResult = unchecked((int)0x80131520); private static void ConstructorTest<T>( int expectedHResult, Func<T> createDefault, Func<string, T> createWithMessage, Func<string, Exception, T> createWithMessageAndException) where T : Exception { var ex = createDefault(); Assert.False(string.IsNullOrEmpty(ex.Message)); Assert.Null(ex.InnerException); Assert.Equal(expectedHResult, ex.HResult); var message = "foo"; ex = createWithMessage(message); Assert.Equal(message, ex.Message); Assert.Null(ex.InnerException); Assert.Equal(expectedHResult, ex.HResult); var innerException = new Exception(); ex = createWithMessageAndException(message, innerException); Assert.Equal(message, ex.Message); Assert.Equal(innerException, ex.InnerException); Assert.Equal(expectedHResult, ex.HResult); } [Fact] public static void ThreadInterruptedException_ConstructorTest() { ConstructorTest<ThreadInterruptedException>( ThreadInterruptedException_HResult, () => new ThreadInterruptedException(), message => new ThreadInterruptedException(message), (message, innerException) => new ThreadInterruptedException(message, innerException)); } [Fact] public static void ThreadStateException_ConstructorTest() { ConstructorTest<ThreadStateException>( ThreadStateException_HResult, () => new ThreadStateException(), message => new ThreadStateException(message), (message, innerException) => new ThreadStateException(message, innerException)); } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Ssl { internal const int SSL_TLSEXT_ERR_OK = 0; internal const int OPENSSL_NPN_NEGOTIATED = 1; internal const int SSL_TLSEXT_ERR_ALERT_FATAL = 2; internal const int SSL_TLSEXT_ERR_NOACK = 3; [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")] internal static partial void EnsureLibSslInitialized(); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")] internal static partial IntPtr SslV2_3Method(); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")] internal static partial SafeSslHandle SslCreate(SafeSslContextHandle ctx); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static partial SslErrorCode SslGetError(SafeSslHandle ssl, int ret); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static partial SslErrorCode SslGetError(IntPtr ssl, int ret); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetQuietShutdown")] internal static partial void SslSetQuietShutdown(SafeSslHandle ssl, int mode); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")] internal static partial void SslDestroy(IntPtr ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")] internal static partial void SslSetConnectState(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")] internal static partial void SslSetAcceptState(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAlpnProtos")] internal static unsafe partial int SslSetAlpnProtos(SafeSslHandle ssl, byte* protos, int len); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")] internal static partial IntPtr SslGetVersion(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetTlsExtHostName", StringMarshalling = StringMarshalling.Utf8)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslSetTlsExtHostName(SafeSslHandle ssl, string host); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGet0AlpnSelected")] internal static partial void SslGetAlpnSelected(SafeSslHandle ssl, out IntPtr protocol, out int len); internal static byte[]? SslGetAlpnSelected(SafeSslHandle ssl) { IntPtr protocol; int len; SslGetAlpnSelected(ssl, out protocol, out len); if (len == 0) return null; byte[] result = new byte[len]; Marshal.Copy(protocol, result, 0, len); return result; } [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite", SetLastError = true)] internal static partial int SslWrite(SafeSslHandle ssl, ref byte buf, int num, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead", SetLastError = true)] internal static partial int SslRead(SafeSslHandle ssl, ref byte buf, int num, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRenegotiate")] internal static partial int SslRenegotiate(SafeSslHandle ssl, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool IsSslRenegotiatePending(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] internal static partial int SslShutdown(IntPtr ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] internal static partial int SslShutdown(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")] internal static partial void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake", SetLastError = true)] internal static partial int SslDoHandshake(SafeSslHandle ssl, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool IsSslStateOK(SafeSslHandle ssl); // NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs. [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] internal static unsafe partial int BioWrite(SafeBioHandle b, byte* data, int len); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] internal static partial int BioWrite(SafeBioHandle b, ref byte data, int len); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")] internal static partial SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")] internal static partial SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")] internal static partial int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")] internal static partial int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslSessionReused(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")] private static partial SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetCurrentCipherId")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslGetCurrentCipherId(SafeSslHandle ssl, out int cipherId); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetOpenSslCipherSuiteName")] private static partial IntPtr GetOpenSslCipherSuiteName(SafeSslHandle ssl, int cipherSuite, out int isTls12OrLower); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetCiphers")] [return: MarshalAs(UnmanagedType.Bool)] internal static unsafe partial bool SslSetCiphers(SafeSslHandle ssl, byte* cipherList, byte* cipherSuites); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetVerifyPeer")] internal static partial void SslSetVerifyPeer(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetData")] internal static partial IntPtr SslGetData(IntPtr ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetData")] internal static partial int SslSetData(SafeSslHandle ssl, IntPtr data); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetData")] internal static partial int SslSetData(IntPtr ssl, IntPtr data); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslUseCertificate")] internal static partial int SslUseCertificate(SafeSslHandle ssl, SafeX509Handle certPtr); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslUsePrivateKey")] internal static partial int SslUsePrivateKey(SafeSslHandle ssl, SafeEvpPKeyHandle keyPtr); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetClientCertCallback")] internal static unsafe partial void SslSetClientCertCallback(SafeSslHandle ssl, int set); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetPostHandshakeAuth")] internal static partial void SslSetPostHandshakeAuth(SafeSslHandle ssl, int value); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Tls13Supported")] private static partial int Tls13SupportedImpl(); internal static class Capabilities { // needs separate type (separate static cctor) to be sure OpenSSL is initialized. internal static readonly bool Tls13Supported = Tls13SupportedImpl() != 0; } internal static int GetAlpnProtocolListSerializedLength(List<SslApplicationProtocol> applicationProtocols) { int protocolSize = 0; foreach (SslApplicationProtocol protocol in applicationProtocols) { if (protocol.Protocol.Length == 0 || protocol.Protocol.Length > byte.MaxValue) { throw new ArgumentException(SR.net_ssl_app_protocols_invalid, nameof(applicationProtocols)); } protocolSize += protocol.Protocol.Length + 1; } return protocolSize; } internal static void SerializeAlpnProtocolList(List<SslApplicationProtocol> applicationProtocols, Span<byte> buffer) { Debug.Assert(GetAlpnProtocolListSerializedLength(applicationProtocols) == buffer.Length, "GetAlpnProtocolListSerializedSize(applicationProtocols) == buffer.Length"); int offset = 0; foreach (SslApplicationProtocol protocol in applicationProtocols) { buffer[offset++] = (byte)protocol.Protocol.Length; protocol.Protocol.Span.CopyTo(buffer.Slice(offset)); offset += protocol.Protocol.Length; } } internal static unsafe int SslSetAlpnProtos(SafeSslHandle ssl, List<SslApplicationProtocol> applicationProtocols) { int length = GetAlpnProtocolListSerializedLength(applicationProtocols); Span<byte> buffer = length <= 256 ? stackalloc byte[256].Slice(0, length) : new byte[length]; SerializeAlpnProtocolList(applicationProtocols, buffer); return SslSetAlpnProtos(ssl, buffer); } internal static unsafe int SslSetAlpnProtos(SafeSslHandle ssl, Span<byte> serializedProtocols) { fixed (byte* pBuffer = &MemoryMarshal.GetReference(serializedProtocols)) { return SslSetAlpnProtos(ssl, pBuffer, serializedProtocols.Length); } } [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddClientCAs")] [return: MarshalAs(UnmanagedType.Bool)] private static unsafe partial bool SslAddClientCAs(SafeSslHandle ssl, IntPtr* x509s, int count); internal static unsafe bool SslAddClientCAs(SafeSslHandle ssl, Span<IntPtr> x509handles) { fixed (IntPtr* pHandles = &MemoryMarshal.GetReference(x509handles)) { return SslAddClientCAs(ssl, pHandles, x509handles.Length); } } internal static bool AddExtraChainCertificates(SafeSslHandle ssl, X509Certificate2[] chain) { // send pre-computed list of intermediates. for (int i = 0; i < chain.Length; i++) { SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain[i].Handle); Crypto.CheckValidOpenSslHandle(dupCertHandle); if (!SslAddExtraChainCert(ssl, dupCertHandle)) { Crypto.ErrClearError(); dupCertHandle.Dispose(); // we still own the safe handle; clean it up return false; } dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle } return true; } internal static string? GetOpenSslCipherSuiteName(SafeSslHandle ssl, TlsCipherSuite cipherSuite, out bool isTls12OrLower) { string? ret = Marshal.PtrToStringAnsi(GetOpenSslCipherSuiteName(ssl, (int)cipherSuite, out int isTls12OrLowerInt)); isTls12OrLower = isTls12OrLowerInt != 0; return ret; } internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl) { Crypto.CheckValidOpenSslHandle(ssl); SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl); if (!handle.IsInvalid) { handle.SetParent(ssl); } return handle; } internal static class SslMethods { internal static readonly IntPtr SSLv23_method = SslV2_3Method(); } internal enum SslErrorCode { SSL_ERROR_NONE = 0, SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, SSL_ERROR_WANT_X509_LOOKUP = 4, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, // NOTE: this SslErrorCode value doesn't exist in OpenSSL, but // we use it to distinguish when a renegotiation is pending. // Choosing an arbitrarily large value that shouldn't conflict // with any actual OpenSSL error codes SSL_ERROR_RENEGOTIATE = 29304 } } } namespace Microsoft.Win32.SafeHandles { internal sealed class SafeSslHandle : SafeHandle { private SafeBioHandle? _readBio; private SafeBioHandle? _writeBio; private bool _isServer; private bool _handshakeCompleted; public GCHandle AlpnHandle; public bool IsServer { get { return _isServer; } } public SafeBioHandle? InputBio { get { return _readBio; } } public SafeBioHandle? OutputBio { get { return _writeBio; } } internal void MarkHandshakeCompleted() { _handshakeCompleted = true; } public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer) { SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio(); SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio(); SafeSslHandle handle = Interop.Ssl.SslCreate(context); if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid) { readBio.Dispose(); writeBio.Dispose(); handle.Dispose(); // will make IsInvalid==true if it's not already return handle; } handle._isServer = isServer; // SslSetBio will transfer ownership of the BIO handles to the SSL context try { readBio.TransferOwnershipToParent(handle); writeBio.TransferOwnershipToParent(handle); handle._readBio = readBio; handle._writeBio = writeBio; Interop.Ssl.SslSetBio(handle, readBio, writeBio); } catch (Exception exc) { // The only way this should be able to happen without thread aborts is if we hit OOMs while // manipulating the safe handles, in which case we may leak the bio handles. Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString()); throw; } if (isServer) { Interop.Ssl.SslSetAcceptState(handle); } else { Interop.Ssl.SslSetConnectState(handle); } return handle; } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override void Dispose(bool disposing) { if (disposing) { _readBio?.Dispose(); _writeBio?.Dispose(); } if (AlpnHandle.IsAllocated) { AlpnHandle.Free(); } base.Dispose(disposing); } protected override bool ReleaseHandle() { if (_handshakeCompleted) { Disconnect(); } IntPtr h = handle; SetHandle(IntPtr.Zero); Interop.Ssl.SslDestroy(h); // will free the handles underlying _readBio and _writeBio return true; } private void Disconnect() { Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect"); int retVal = Interop.Ssl.SslShutdown(handle); // Here, we are ignoring checking for <0 return values from Ssl_Shutdown, // since the underlying memory bio is already disposed, we are not // interested in reading or writing to it. if (retVal == 0) { // Do a bi-directional shutdown. retVal = Interop.Ssl.SslShutdown(handle); } if (retVal < 0) { // Clean up the errors Interop.Crypto.ErrClearError(); } } public SafeSslHandle() : base(IntPtr.Zero, true) { } internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { handle = validSslPointer; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Ssl { internal const int SSL_TLSEXT_ERR_OK = 0; internal const int OPENSSL_NPN_NEGOTIATED = 1; internal const int SSL_TLSEXT_ERR_ALERT_FATAL = 2; internal const int SSL_TLSEXT_ERR_NOACK = 3; [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")] internal static partial void EnsureLibSslInitialized(); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")] internal static partial IntPtr SslV2_3Method(); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")] internal static partial SafeSslHandle SslCreate(SafeSslContextHandle ctx); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static partial SslErrorCode SslGetError(SafeSslHandle ssl, int ret); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static partial SslErrorCode SslGetError(IntPtr ssl, int ret); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetQuietShutdown")] internal static partial void SslSetQuietShutdown(SafeSslHandle ssl, int mode); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")] internal static partial void SslDestroy(IntPtr ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")] internal static partial void SslSetConnectState(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")] internal static partial void SslSetAcceptState(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAlpnProtos")] internal static unsafe partial int SslSetAlpnProtos(SafeSslHandle ssl, byte* protos, int len); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")] internal static partial IntPtr SslGetVersion(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetTlsExtHostName", StringMarshalling = StringMarshalling.Utf8)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslSetTlsExtHostName(SafeSslHandle ssl, string host); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGet0AlpnSelected")] internal static partial void SslGetAlpnSelected(SafeSslHandle ssl, out IntPtr protocol, out int len); internal static byte[]? SslGetAlpnSelected(SafeSslHandle ssl) { IntPtr protocol; int len; SslGetAlpnSelected(ssl, out protocol, out len); if (len == 0) return null; byte[] result = new byte[len]; Marshal.Copy(protocol, result, 0, len); return result; } [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite", SetLastError = true)] internal static partial int SslWrite(SafeSslHandle ssl, ref byte buf, int num, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead", SetLastError = true)] internal static partial int SslRead(SafeSslHandle ssl, ref byte buf, int num, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRenegotiate")] internal static partial int SslRenegotiate(SafeSslHandle ssl, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool IsSslRenegotiatePending(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] internal static partial int SslShutdown(IntPtr ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] internal static partial int SslShutdown(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")] internal static partial void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake", SetLastError = true)] internal static partial int SslDoHandshake(SafeSslHandle ssl, out SslErrorCode error); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool IsSslStateOK(SafeSslHandle ssl); // NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs. [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] internal static unsafe partial int BioWrite(SafeBioHandle b, byte* data, int len); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] internal static partial int BioWrite(SafeBioHandle b, ref byte data, int len); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")] internal static partial SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")] internal static partial SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")] internal static partial int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")] internal static partial int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslSessionReused(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")] private static partial SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetCurrentCipherId")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslGetCurrentCipherId(SafeSslHandle ssl, out int cipherId); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetOpenSslCipherSuiteName")] private static partial IntPtr GetOpenSslCipherSuiteName(SafeSslHandle ssl, int cipherSuite, out int isTls12OrLower); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetCiphers")] [return: MarshalAs(UnmanagedType.Bool)] internal static unsafe partial bool SslSetCiphers(SafeSslHandle ssl, byte* cipherList, byte* cipherSuites); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetVerifyPeer")] internal static partial void SslSetVerifyPeer(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetData")] internal static partial IntPtr SslGetData(IntPtr ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetData")] internal static partial int SslSetData(SafeSslHandle ssl, IntPtr data); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetData")] internal static partial int SslSetData(IntPtr ssl, IntPtr data); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslUseCertificate")] internal static partial int SslUseCertificate(SafeSslHandle ssl, SafeX509Handle certPtr); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslUsePrivateKey")] internal static partial int SslUsePrivateKey(SafeSslHandle ssl, SafeEvpPKeyHandle keyPtr); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetClientCertCallback")] internal static unsafe partial void SslSetClientCertCallback(SafeSslHandle ssl, int set); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetPostHandshakeAuth")] internal static partial void SslSetPostHandshakeAuth(SafeSslHandle ssl, int value); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Tls13Supported")] private static partial int Tls13SupportedImpl(); internal static class Capabilities { // needs separate type (separate static cctor) to be sure OpenSSL is initialized. internal static readonly bool Tls13Supported = Tls13SupportedImpl() != 0; } internal static int GetAlpnProtocolListSerializedLength(List<SslApplicationProtocol> applicationProtocols) { int protocolSize = 0; foreach (SslApplicationProtocol protocol in applicationProtocols) { if (protocol.Protocol.Length == 0 || protocol.Protocol.Length > byte.MaxValue) { throw new ArgumentException(SR.net_ssl_app_protocols_invalid, nameof(applicationProtocols)); } protocolSize += protocol.Protocol.Length + 1; } return protocolSize; } internal static void SerializeAlpnProtocolList(List<SslApplicationProtocol> applicationProtocols, Span<byte> buffer) { Debug.Assert(GetAlpnProtocolListSerializedLength(applicationProtocols) == buffer.Length, "GetAlpnProtocolListSerializedSize(applicationProtocols) == buffer.Length"); int offset = 0; foreach (SslApplicationProtocol protocol in applicationProtocols) { buffer[offset++] = (byte)protocol.Protocol.Length; protocol.Protocol.Span.CopyTo(buffer.Slice(offset)); offset += protocol.Protocol.Length; } } internal static unsafe int SslSetAlpnProtos(SafeSslHandle ssl, List<SslApplicationProtocol> applicationProtocols) { int length = GetAlpnProtocolListSerializedLength(applicationProtocols); Span<byte> buffer = length <= 256 ? stackalloc byte[256].Slice(0, length) : new byte[length]; SerializeAlpnProtocolList(applicationProtocols, buffer); return SslSetAlpnProtos(ssl, buffer); } internal static unsafe int SslSetAlpnProtos(SafeSslHandle ssl, Span<byte> serializedProtocols) { fixed (byte* pBuffer = &MemoryMarshal.GetReference(serializedProtocols)) { return SslSetAlpnProtos(ssl, pBuffer, serializedProtocols.Length); } } [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddClientCAs")] [return: MarshalAs(UnmanagedType.Bool)] private static unsafe partial bool SslAddClientCAs(SafeSslHandle ssl, IntPtr* x509s, int count); internal static unsafe bool SslAddClientCAs(SafeSslHandle ssl, Span<IntPtr> x509handles) { fixed (IntPtr* pHandles = &MemoryMarshal.GetReference(x509handles)) { return SslAddClientCAs(ssl, pHandles, x509handles.Length); } } internal static bool AddExtraChainCertificates(SafeSslHandle ssl, X509Certificate2[] chain) { // send pre-computed list of intermediates. for (int i = 0; i < chain.Length; i++) { SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain[i].Handle); Crypto.CheckValidOpenSslHandle(dupCertHandle); if (!SslAddExtraChainCert(ssl, dupCertHandle)) { Crypto.ErrClearError(); dupCertHandle.Dispose(); // we still own the safe handle; clean it up return false; } dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle } return true; } internal static string? GetOpenSslCipherSuiteName(SafeSslHandle ssl, TlsCipherSuite cipherSuite, out bool isTls12OrLower) { string? ret = Marshal.PtrToStringAnsi(GetOpenSslCipherSuiteName(ssl, (int)cipherSuite, out int isTls12OrLowerInt)); isTls12OrLower = isTls12OrLowerInt != 0; return ret; } internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl) { Crypto.CheckValidOpenSslHandle(ssl); SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl); if (!handle.IsInvalid) { handle.SetParent(ssl); } return handle; } internal static class SslMethods { internal static readonly IntPtr SSLv23_method = SslV2_3Method(); } internal enum SslErrorCode { SSL_ERROR_NONE = 0, SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, SSL_ERROR_WANT_X509_LOOKUP = 4, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, // NOTE: this SslErrorCode value doesn't exist in OpenSSL, but // we use it to distinguish when a renegotiation is pending. // Choosing an arbitrarily large value that shouldn't conflict // with any actual OpenSSL error codes SSL_ERROR_RENEGOTIATE = 29304 } } } namespace Microsoft.Win32.SafeHandles { internal sealed class SafeSslHandle : SafeHandle { private SafeBioHandle? _readBio; private SafeBioHandle? _writeBio; private bool _isServer; private bool _handshakeCompleted; public GCHandle AlpnHandle; public bool IsServer { get { return _isServer; } } public SafeBioHandle? InputBio { get { return _readBio; } } public SafeBioHandle? OutputBio { get { return _writeBio; } } internal void MarkHandshakeCompleted() { _handshakeCompleted = true; } public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer) { SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio(); SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio(); SafeSslHandle handle = Interop.Ssl.SslCreate(context); if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid) { readBio.Dispose(); writeBio.Dispose(); handle.Dispose(); // will make IsInvalid==true if it's not already return handle; } handle._isServer = isServer; // SslSetBio will transfer ownership of the BIO handles to the SSL context try { readBio.TransferOwnershipToParent(handle); writeBio.TransferOwnershipToParent(handle); handle._readBio = readBio; handle._writeBio = writeBio; Interop.Ssl.SslSetBio(handle, readBio, writeBio); } catch (Exception exc) { // The only way this should be able to happen without thread aborts is if we hit OOMs while // manipulating the safe handles, in which case we may leak the bio handles. Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString()); throw; } if (isServer) { Interop.Ssl.SslSetAcceptState(handle); } else { Interop.Ssl.SslSetConnectState(handle); } return handle; } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override void Dispose(bool disposing) { if (disposing) { _readBio?.Dispose(); _writeBio?.Dispose(); } if (AlpnHandle.IsAllocated) { AlpnHandle.Free(); } base.Dispose(disposing); } protected override bool ReleaseHandle() { if (_handshakeCompleted) { Disconnect(); } IntPtr h = handle; SetHandle(IntPtr.Zero); Interop.Ssl.SslDestroy(h); // will free the handles underlying _readBio and _writeBio return true; } private void Disconnect() { Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect"); int retVal = Interop.Ssl.SslShutdown(handle); // Here, we are ignoring checking for <0 return values from Ssl_Shutdown, // since the underlying memory bio is already disposed, we are not // interested in reading or writing to it. if (retVal == 0) { // Do a bi-directional shutdown. retVal = Interop.Ssl.SslShutdown(handle); } if (retVal < 0) { // Clean up the errors Interop.Crypto.ErrClearError(); } } public SafeSslHandle() : base(IntPtr.Zero, true) { } internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { handle = validSslPointer; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/TestService.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.Pipes; using System.Threading.Tasks; namespace System.ServiceProcess.Tests { public class TestService : ServiceBase { // To view tracing, use DbgView from sysinternals.com; // run it elevated, check "Capture>Global Win32" and "Capture>Win32", // and filter to just messages beginning with "##" internal const bool DebugTracing = false; // toggle in TestServiceProvider.cs as well private bool _disposed; private Task _waitClientConnect; private NamedPipeServerStream _serverStream; private readonly Exception _exception; public TestService(string serviceName, Exception throwException = null) { DebugTrace("TestService " + ServiceName + ": Ctor"); this.ServiceName = serviceName; // Enable all the events this.CanPauseAndContinue = true; this.CanStop = true; this.CanShutdown = true; // We cannot easily test these so disable the events this.CanHandleSessionChangeEvent = false; this.CanHandlePowerEvent = false; this._exception = throwException; this._serverStream = new NamedPipeServerStream(serviceName); _waitClientConnect = this._serverStream.WaitForConnectionAsync(); _waitClientConnect = _waitClientConnect.ContinueWith(_ => DebugTrace("TestService " + ServiceName + ": Connected")); _waitClientConnect = _waitClientConnect.ContinueWith(t => WriteStreamAsync(PipeMessageByteCode.Connected, waitForConnect: false)); DebugTrace("TestService " + ServiceName + ": Ctor completed"); } protected override void OnContinue() { base.OnContinue(); WriteStreamAsync(PipeMessageByteCode.Continue).Wait(); } protected override void OnCustomCommand(int command) { base.OnCustomCommand(command); if (Environment.UserInteractive) // see ServiceBaseTests.TestOnExecuteCustomCommand() command++; WriteStreamAsync(PipeMessageByteCode.OnCustomCommand, command).Wait(); } protected override void OnPause() { base.OnPause(); WriteStreamAsync(PipeMessageByteCode.Pause).Wait(); } protected override void OnSessionChange(SessionChangeDescription changeDescription) { base.OnSessionChange(changeDescription); } protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { return base.OnPowerEvent(powerStatus); } protected override void OnShutdown() { base.OnShutdown(); } protected override void OnStart(string[] args) { DebugTrace("TestService " + ServiceName + ": OnStart"); base.OnStart(args); if (_exception != null) { throw _exception; } if (args.Length == 4 && args[0] == "StartWithArguments") { Debug.Assert(args[1] == "a"); Debug.Assert(args[2] == "b"); Debug.Assert(args[3] == "c"); WriteStreamAsync(PipeMessageByteCode.Start).Wait(); } } protected override void OnStop() { DebugTrace("TestService " + ServiceName + ": OnStop"); base.OnStop(); // We may be stopping because the test has completed and we're cleaning up the test service so there's no client at all, so don't waitForConnect. // Tests that verify "Stop" itself should ensure the client connection has completed before calling stop, by waiting on some other message from the pipe first. WriteStreamAsync(PipeMessageByteCode.Stop, waitForConnect:false).Wait(); } public async Task WriteStreamAsync(PipeMessageByteCode code, int command = 0, bool waitForConnect = true) { DebugTrace("TestService " + ServiceName + ": WriteStreamAsync writing " + code.ToString()); var toWrite = (code == PipeMessageByteCode.OnCustomCommand) ? new byte[] { (byte)command } : new byte[] { (byte)code }; // Wait for the client connection before writing to the pipe. if (waitForConnect) { await _waitClientConnect; } await _serverStream.WriteAsync(toWrite, 0, 1).WaitAsync(TimeSpan.FromSeconds(60)).ConfigureAwait(false); DebugTrace("TestService " + ServiceName + ": WriteStreamAsync completed"); } /// <summary> /// This is called from <see cref="ServiceBase.Run(ServiceBase[])"/> when all services in the process /// have entered the SERVICE_STOPPED state. It disposes the named pipe stream. /// </summary> protected override void Dispose(bool disposing) { if (!_disposed) { DebugTrace("TestService " + ServiceName + ": Disposing"); _serverStream.Dispose(); _disposed = true; base.Dispose(); } } internal static void DebugTrace(string message) { if (DebugTracing) { #pragma warning disable CS0162 // unreachable code Debug.WriteLine("## " + message); #pragma warning restore } } } }
// 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.Pipes; using System.Threading.Tasks; namespace System.ServiceProcess.Tests { public class TestService : ServiceBase { // To view tracing, use DbgView from sysinternals.com; // run it elevated, check "Capture>Global Win32" and "Capture>Win32", // and filter to just messages beginning with "##" internal const bool DebugTracing = false; // toggle in TestServiceProvider.cs as well private bool _disposed; private Task _waitClientConnect; private NamedPipeServerStream _serverStream; private readonly Exception _exception; public TestService(string serviceName, Exception throwException = null) { DebugTrace("TestService " + ServiceName + ": Ctor"); this.ServiceName = serviceName; // Enable all the events this.CanPauseAndContinue = true; this.CanStop = true; this.CanShutdown = true; // We cannot easily test these so disable the events this.CanHandleSessionChangeEvent = false; this.CanHandlePowerEvent = false; this._exception = throwException; this._serverStream = new NamedPipeServerStream(serviceName); _waitClientConnect = this._serverStream.WaitForConnectionAsync(); _waitClientConnect = _waitClientConnect.ContinueWith(_ => DebugTrace("TestService " + ServiceName + ": Connected")); _waitClientConnect = _waitClientConnect.ContinueWith(t => WriteStreamAsync(PipeMessageByteCode.Connected, waitForConnect: false)); DebugTrace("TestService " + ServiceName + ": Ctor completed"); } protected override void OnContinue() { base.OnContinue(); WriteStreamAsync(PipeMessageByteCode.Continue).Wait(); } protected override void OnCustomCommand(int command) { base.OnCustomCommand(command); if (Environment.UserInteractive) // see ServiceBaseTests.TestOnExecuteCustomCommand() command++; WriteStreamAsync(PipeMessageByteCode.OnCustomCommand, command).Wait(); } protected override void OnPause() { base.OnPause(); WriteStreamAsync(PipeMessageByteCode.Pause).Wait(); } protected override void OnSessionChange(SessionChangeDescription changeDescription) { base.OnSessionChange(changeDescription); } protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { return base.OnPowerEvent(powerStatus); } protected override void OnShutdown() { base.OnShutdown(); } protected override void OnStart(string[] args) { DebugTrace("TestService " + ServiceName + ": OnStart"); base.OnStart(args); if (_exception != null) { throw _exception; } if (args.Length == 4 && args[0] == "StartWithArguments") { Debug.Assert(args[1] == "a"); Debug.Assert(args[2] == "b"); Debug.Assert(args[3] == "c"); WriteStreamAsync(PipeMessageByteCode.Start).Wait(); } } protected override void OnStop() { DebugTrace("TestService " + ServiceName + ": OnStop"); base.OnStop(); // We may be stopping because the test has completed and we're cleaning up the test service so there's no client at all, so don't waitForConnect. // Tests that verify "Stop" itself should ensure the client connection has completed before calling stop, by waiting on some other message from the pipe first. WriteStreamAsync(PipeMessageByteCode.Stop, waitForConnect:false).Wait(); } public async Task WriteStreamAsync(PipeMessageByteCode code, int command = 0, bool waitForConnect = true) { DebugTrace("TestService " + ServiceName + ": WriteStreamAsync writing " + code.ToString()); var toWrite = (code == PipeMessageByteCode.OnCustomCommand) ? new byte[] { (byte)command } : new byte[] { (byte)code }; // Wait for the client connection before writing to the pipe. if (waitForConnect) { await _waitClientConnect; } await _serverStream.WriteAsync(toWrite, 0, 1).WaitAsync(TimeSpan.FromSeconds(60)).ConfigureAwait(false); DebugTrace("TestService " + ServiceName + ": WriteStreamAsync completed"); } /// <summary> /// This is called from <see cref="ServiceBase.Run(ServiceBase[])"/> when all services in the process /// have entered the SERVICE_STOPPED state. It disposes the named pipe stream. /// </summary> protected override void Dispose(bool disposing) { if (!_disposed) { DebugTrace("TestService " + ServiceName + ": Disposing"); _serverStream.Dispose(); _disposed = true; base.Dispose(); } } internal static void DebugTrace(string message) { if (DebugTracing) { #pragma warning disable CS0162 // unreachable code Debug.WriteLine("## " + message); #pragma warning restore } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.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.CodeAnalysis; namespace System.Reflection { public static partial class RuntimeReflectionExtensions { private const BindingFlags Everything = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; public static IEnumerable<FieldInfo> GetRuntimeFields( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type!!) { return type.GetFields(Everything); } public static IEnumerable<MethodInfo> GetRuntimeMethods( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type!!) { return type.GetMethods(Everything); } public static IEnumerable<PropertyInfo> GetRuntimeProperties( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type!!) { return type.GetProperties(Everything); } public static IEnumerable<EventInfo> GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type!!) { return type.GetEvents(Everything); } public static FieldInfo? GetRuntimeField( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type!!, string name) { return type.GetField(name); } public static MethodInfo? GetRuntimeMethod( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type!!, string name, Type[] parameters) { return type.GetMethod(name, parameters); } public static PropertyInfo? GetRuntimeProperty( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type!!, string name) { return type.GetProperty(name); } public static EventInfo? GetRuntimeEvent( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type!!, string name) { return type.GetEvent(name); } public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method!!) { return method.GetBaseDefinition(); } public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo!!, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { return typeInfo.GetInterfaceMap(interfaceType); } public static MethodInfo GetMethodInfo(this Delegate del!!) { return del.Method; } } }
// 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.CodeAnalysis; namespace System.Reflection { public static partial class RuntimeReflectionExtensions { private const BindingFlags Everything = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; public static IEnumerable<FieldInfo> GetRuntimeFields( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type!!) { return type.GetFields(Everything); } public static IEnumerable<MethodInfo> GetRuntimeMethods( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type!!) { return type.GetMethods(Everything); } public static IEnumerable<PropertyInfo> GetRuntimeProperties( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type!!) { return type.GetProperties(Everything); } public static IEnumerable<EventInfo> GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type!!) { return type.GetEvents(Everything); } public static FieldInfo? GetRuntimeField( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type!!, string name) { return type.GetField(name); } public static MethodInfo? GetRuntimeMethod( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type!!, string name, Type[] parameters) { return type.GetMethod(name, parameters); } public static PropertyInfo? GetRuntimeProperty( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type!!, string name) { return type.GetProperty(name); } public static EventInfo? GetRuntimeEvent( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type!!, string name) { return type.GetEvent(name); } public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method!!) { return method.GetBaseDefinition(); } public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo!!, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { return typeInfo.GetInterfaceMap(interfaceType); } public static MethodInfo GetMethodInfo(this Delegate del!!) { return del.Method; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileSystemInfoBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.FileSystemGlobbing.Abstractions { /// <summary> /// Shared abstraction for files and directories /// </summary> public abstract class FileSystemInfoBase { /// <summary> /// A string containing the name of the file or directory /// </summary> public abstract string Name { get; } /// <summary> /// A string containing the full path of the file or directory /// </summary> public abstract string FullName { get; } /// <summary> /// The parent directory for the current file or directory /// </summary> public abstract DirectoryInfoBase? ParentDirectory { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.FileSystemGlobbing.Abstractions { /// <summary> /// Shared abstraction for files and directories /// </summary> public abstract class FileSystemInfoBase { /// <summary> /// A string containing the name of the file or directory /// </summary> public abstract string Name { get; } /// <summary> /// A string containing the full path of the file or directory /// </summary> public abstract string FullName { get; } /// <summary> /// The parent directory for the current file or directory /// </summary> public abstract DirectoryInfoBase? ParentDirectory { get; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_UnaryPlus.Int64.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_UnaryPlusInt64() { var test = new VectorUnaryOpTest__op_UnaryPlusInt64(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorUnaryOpTest__op_UnaryPlusInt64 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, 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 Vector256<Int64> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_UnaryPlusInt64 testClass) { var result = +_fld1; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Vector256<Int64> _clsVar1; private Vector256<Int64> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_UnaryPlusInt64() { 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>>()); } public VectorUnaryOpTest__op_UnaryPlusInt64() { 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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, new Int64[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = +Unsafe.Read<Vector256<Int64>>(_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(Vector256<Int64>).GetMethod("op_UnaryPlus", new Type[] { typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = +_clsVar1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var result = +op1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__op_UnaryPlusInt64(); var result = +test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = +_fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = +test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int64> op1, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (long)(+firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (long)(+firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_UnaryPlus<Int64>(Vector256<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_UnaryPlusInt64() { var test = new VectorUnaryOpTest__op_UnaryPlusInt64(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorUnaryOpTest__op_UnaryPlusInt64 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, 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 Vector256<Int64> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_UnaryPlusInt64 testClass) { var result = +_fld1; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Vector256<Int64> _clsVar1; private Vector256<Int64> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_UnaryPlusInt64() { 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>>()); } public VectorUnaryOpTest__op_UnaryPlusInt64() { 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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, new Int64[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = +Unsafe.Read<Vector256<Int64>>(_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(Vector256<Int64>).GetMethod("op_UnaryPlus", new Type[] { typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = +_clsVar1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var result = +op1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__op_UnaryPlusInt64(); var result = +test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = +_fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = +test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int64> op1, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (long)(+firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (long)(+firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_UnaryPlus<Int64>(Vector256<Int64>): {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,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ExclusiveOrInstruction.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.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class ExclusiveOrInstruction : Instruction { private static Instruction? s_SByte, s_Int16, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Boolean; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "ExclusiveOr"; private ExclusiveOrInstruction() { } private sealed class ExclusiveOrSByte : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((sbyte)((sbyte)left ^ (sbyte)right)); return 1; } } private sealed class ExclusiveOrInt16 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((short)((short)left ^ (short)right)); return 1; } } private sealed class ExclusiveOrInt32 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((int)left ^ (int)right); return 1; } } private sealed class ExclusiveOrInt64 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((long)left ^ (long)right); return 1; } } private sealed class ExclusiveOrByte : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((byte)((byte)left ^ (byte)right)); return 1; } } private sealed class ExclusiveOrUInt16 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((ushort)((ushort)left ^ (ushort)right)); return 1; } } private sealed class ExclusiveOrUInt32 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((uint)left ^ (uint)right); return 1; } } private sealed class ExclusiveOrUInt64 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((ulong)left ^ (ulong)right); return 1; } } private sealed class ExclusiveOrBoolean : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((bool)left ^ (bool)right); return 1; } } public static Instruction Create(Type type) => type.GetNonNullableType().GetTypeCode() switch { TypeCode.SByte => s_SByte ?? (s_SByte = new ExclusiveOrSByte()), TypeCode.Int16 => s_Int16 ?? (s_Int16 = new ExclusiveOrInt16()), TypeCode.Int32 => s_Int32 ?? (s_Int32 = new ExclusiveOrInt32()), TypeCode.Int64 => s_Int64 ?? (s_Int64 = new ExclusiveOrInt64()), TypeCode.Byte => s_Byte ?? (s_Byte = new ExclusiveOrByte()), TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new ExclusiveOrUInt16()), TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new ExclusiveOrUInt32()), TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new ExclusiveOrUInt64()), TypeCode.Boolean => s_Boolean ?? (s_Boolean = new ExclusiveOrBoolean()), _ => throw ContractUtils.Unreachable, }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class ExclusiveOrInstruction : Instruction { private static Instruction? s_SByte, s_Int16, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Boolean; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "ExclusiveOr"; private ExclusiveOrInstruction() { } private sealed class ExclusiveOrSByte : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((sbyte)((sbyte)left ^ (sbyte)right)); return 1; } } private sealed class ExclusiveOrInt16 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((short)((short)left ^ (short)right)); return 1; } } private sealed class ExclusiveOrInt32 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((int)left ^ (int)right); return 1; } } private sealed class ExclusiveOrInt64 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((long)left ^ (long)right); return 1; } } private sealed class ExclusiveOrByte : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((byte)((byte)left ^ (byte)right)); return 1; } } private sealed class ExclusiveOrUInt16 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((ushort)((ushort)left ^ (ushort)right)); return 1; } } private sealed class ExclusiveOrUInt32 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((uint)left ^ (uint)right); return 1; } } private sealed class ExclusiveOrUInt64 : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((ulong)left ^ (ulong)right); return 1; } } private sealed class ExclusiveOrBoolean : ExclusiveOrInstruction { public override int Run(InterpretedFrame frame) { object? left = frame.Pop(); object? right = frame.Pop(); if (left == null || right == null) { frame.Push(null); return 1; } frame.Push((bool)left ^ (bool)right); return 1; } } public static Instruction Create(Type type) => type.GetNonNullableType().GetTypeCode() switch { TypeCode.SByte => s_SByte ?? (s_SByte = new ExclusiveOrSByte()), TypeCode.Int16 => s_Int16 ?? (s_Int16 = new ExclusiveOrInt16()), TypeCode.Int32 => s_Int32 ?? (s_Int32 = new ExclusiveOrInt32()), TypeCode.Int64 => s_Int64 ?? (s_Int64 = new ExclusiveOrInt64()), TypeCode.Byte => s_Byte ?? (s_Byte = new ExclusiveOrByte()), TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new ExclusiveOrUInt16()), TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new ExclusiveOrUInt32()), TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new ExclusiveOrUInt64()), TypeCode.Boolean => s_Boolean ?? (s_Boolean = new ExclusiveOrBoolean()), _ => throw ContractUtils.Unreachable, }; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Linq/src/System/Linq/Lookup.SpeedOpt.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Linq { public partial class Lookup<TKey, TElement> : IIListProvider<IGrouping<TKey, TElement>> { IGrouping<TKey, TElement>[] IIListProvider<IGrouping<TKey, TElement>>.ToArray() { IGrouping<TKey, TElement>[] array = new IGrouping<TKey, TElement>[_count]; int index = 0; Grouping<TKey, TElement>? g = _lastGrouping; if (g != null) { do { g = g._next; Debug.Assert(g != null); array[index] = g; ++index; } while (g != _lastGrouping); } return array; } internal TResult[] ToArray<TResult>(Func<TKey, IEnumerable<TElement>, TResult> resultSelector) { TResult[] array = new TResult[_count]; int index = 0; Grouping<TKey, TElement>? g = _lastGrouping; if (g != null) { do { g = g._next; Debug.Assert(g != null); g.Trim(); array[index] = resultSelector(g._key, g._elements); ++index; } while (g != _lastGrouping); } return array; } List<IGrouping<TKey, TElement>> IIListProvider<IGrouping<TKey, TElement>>.ToList() { List<IGrouping<TKey, TElement>> list = new List<IGrouping<TKey, TElement>>(_count); Grouping<TKey, TElement>? g = _lastGrouping; if (g != null) { do { g = g._next; Debug.Assert(g != null); list.Add(g); } while (g != _lastGrouping); } return list; } int IIListProvider<IGrouping<TKey, TElement>>.GetCount(bool onlyIfCheap) => _count; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Linq { public partial class Lookup<TKey, TElement> : IIListProvider<IGrouping<TKey, TElement>> { IGrouping<TKey, TElement>[] IIListProvider<IGrouping<TKey, TElement>>.ToArray() { IGrouping<TKey, TElement>[] array = new IGrouping<TKey, TElement>[_count]; int index = 0; Grouping<TKey, TElement>? g = _lastGrouping; if (g != null) { do { g = g._next; Debug.Assert(g != null); array[index] = g; ++index; } while (g != _lastGrouping); } return array; } internal TResult[] ToArray<TResult>(Func<TKey, IEnumerable<TElement>, TResult> resultSelector) { TResult[] array = new TResult[_count]; int index = 0; Grouping<TKey, TElement>? g = _lastGrouping; if (g != null) { do { g = g._next; Debug.Assert(g != null); g.Trim(); array[index] = resultSelector(g._key, g._elements); ++index; } while (g != _lastGrouping); } return array; } List<IGrouping<TKey, TElement>> IIListProvider<IGrouping<TKey, TElement>>.ToList() { List<IGrouping<TKey, TElement>> list = new List<IGrouping<TKey, TElement>>(_count); Grouping<TKey, TElement>? g = _lastGrouping; if (g != null) { do { g = g._next; Debug.Assert(g != null); list.Add(g); } while (g != _lastGrouping); } return list; } int IIListProvider<IGrouping<TKey, TElement>>.GetCount(bool onlyIfCheap) => _count; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Regression/Dev11/External/dev11_132534/StandardSupport.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Test { public struct BasicStruct { public int Field1; public int Field2; public int Field3; public int Field4; public BasicStruct(int field1, int field2, int field3, int field4) { this.Field1 = field1; this.Field2 = field2; this.Field3 = field3; this.Field4 = field4; return; } public override string ToString() { return String.Format( "{0}, {1}, {2}, {3}", this.Field1, this.Field2, this.Field3, this.Field4 ); } public static bool AreEqual(BasicStruct s1, BasicStruct s2) { if ((s1.Field1 == s2.Field1) && (s1.Field2 == s2.Field2) && (s1.Field3 == s2.Field3) && (s1.Field4 == s2.Field4)) { return true; } else { return false; } } } public static class Support { private static Exception SignalVerificationFailure(string kind, string value, string expected) { throw new Exception( String.Format( "FAILED: {0} verification failed.\r\n" + " Observed value: {1}\r\n" + " Expected value: {2}\r\n", kind, value, expected ) ); } public static void VerifyInt(int value, int expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Int", value.ToString(), expected.ToString()); } public static void VerifyLong(long value, long expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Long", value.ToString(), expected.ToString()); } public static void VerifyFloat(float value, float expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Float", value.ToString(), expected.ToString()); } public static void VerifyDouble(double value, double expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Double", value.ToString(), expected.ToString()); } public static void VerifyString(string value, string expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("String", value.ToString(), expected.ToString()); } public static void VerifyStruct(BasicStruct value, BasicStruct expected) { if (BasicStruct.AreEqual(value, expected)) { return; } throw Support.SignalVerificationFailure("Struct", value.ToString(), expected.ToString()); } } public static partial class CallerSide { private static string s_lastExecutedCaller; public static void PrepareForWrapperCall() { CallerSide.s_lastExecutedCaller = null; return; } public static void RecordExecutedCaller(string tag) { if (CallerSide.s_lastExecutedCaller != null) { throw new Exception("Tried to record multiple callers at once."); } CallerSide.s_lastExecutedCaller = tag; return; } public static void VerifyExecutedCaller(string expectedTag) { if (CallerSide.s_lastExecutedCaller != expectedTag) { throw new Exception("The exected caller was not recorded during the last operation."); } return; } public static bool MakeWrapperCall(string functionTag, Action runSpecificWrapper) { Console.WriteLine(" Executing JMP wrapper for: \"{0}\"", functionTag); try { runSpecificWrapper(); } catch (Exception e) { Console.WriteLine(" FAILED: ({0})", e.GetType().ToString()); return false; } Console.WriteLine(" PASSED"); return true; } } internal static class App { private static int Main() { int iret = 100; Console.WriteLine("Starting JMP tests...\r\n"); if (!CallerSide.MakeAllWrapperCalls()) { iret = 1; } Console.WriteLine("\r\nJMP tests are complete.\r\n"); return iret; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Test { public struct BasicStruct { public int Field1; public int Field2; public int Field3; public int Field4; public BasicStruct(int field1, int field2, int field3, int field4) { this.Field1 = field1; this.Field2 = field2; this.Field3 = field3; this.Field4 = field4; return; } public override string ToString() { return String.Format( "{0}, {1}, {2}, {3}", this.Field1, this.Field2, this.Field3, this.Field4 ); } public static bool AreEqual(BasicStruct s1, BasicStruct s2) { if ((s1.Field1 == s2.Field1) && (s1.Field2 == s2.Field2) && (s1.Field3 == s2.Field3) && (s1.Field4 == s2.Field4)) { return true; } else { return false; } } } public static class Support { private static Exception SignalVerificationFailure(string kind, string value, string expected) { throw new Exception( String.Format( "FAILED: {0} verification failed.\r\n" + " Observed value: {1}\r\n" + " Expected value: {2}\r\n", kind, value, expected ) ); } public static void VerifyInt(int value, int expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Int", value.ToString(), expected.ToString()); } public static void VerifyLong(long value, long expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Long", value.ToString(), expected.ToString()); } public static void VerifyFloat(float value, float expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Float", value.ToString(), expected.ToString()); } public static void VerifyDouble(double value, double expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("Double", value.ToString(), expected.ToString()); } public static void VerifyString(string value, string expected) { if (value == expected) { return; } throw Support.SignalVerificationFailure("String", value.ToString(), expected.ToString()); } public static void VerifyStruct(BasicStruct value, BasicStruct expected) { if (BasicStruct.AreEqual(value, expected)) { return; } throw Support.SignalVerificationFailure("Struct", value.ToString(), expected.ToString()); } } public static partial class CallerSide { private static string s_lastExecutedCaller; public static void PrepareForWrapperCall() { CallerSide.s_lastExecutedCaller = null; return; } public static void RecordExecutedCaller(string tag) { if (CallerSide.s_lastExecutedCaller != null) { throw new Exception("Tried to record multiple callers at once."); } CallerSide.s_lastExecutedCaller = tag; return; } public static void VerifyExecutedCaller(string expectedTag) { if (CallerSide.s_lastExecutedCaller != expectedTag) { throw new Exception("The exected caller was not recorded during the last operation."); } return; } public static bool MakeWrapperCall(string functionTag, Action runSpecificWrapper) { Console.WriteLine(" Executing JMP wrapper for: \"{0}\"", functionTag); try { runSpecificWrapper(); } catch (Exception e) { Console.WriteLine(" FAILED: ({0})", e.GetType().ToString()); return false; } Console.WriteLine(" PASSED"); return true; } } internal static class App { private static int Main() { int iret = 100; Console.WriteLine("Starting JMP tests...\r\n"); if (!CallerSide.MakeAllWrapperCalls()) { iret = 1; } Console.WriteLine("\r\nJMP tests are complete.\r\n"); return iret; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Drawing.Common/tests/mono/System.Imaging/MetafileTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // Metafile class unit tests // // Authors: // Sebastien Pouliot <[email protected]> // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // 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. // using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace MonoTests.System.Drawing.Imaging { [ActiveIssue("https://github.com/dotnet/runtime/issues/34591", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public class MetafileTest { public const string Bitmap = "non-inverted.bmp"; public const string WmfPlaceable = "telescope_01.wmf"; public const string Emf = "milkmateya01.emf"; [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_String() { string filename = Helpers.GetTestBitmapPath(WmfPlaceable); using (Metafile mf = new Metafile(filename)) using (Metafile clone = (Metafile)mf.Clone()) { } } private static void Check_MetaHeader_WmfPlaceable(MetaHeader mh) { Assert.Equal(9, mh.HeaderSize); Assert.Equal(98, mh.MaxRecord); Assert.Equal(3, mh.NoObjects); Assert.Equal(0, mh.NoParameters); Assert.Equal(1737, mh.Size); Assert.Equal(1, mh.Type); Assert.Equal(0x300, mh.Version); } private static void Check_MetafileHeader_WmfPlaceable(MetafileHeader header) { Assert.Equal(MetafileType.WmfPlaceable, header.Type); Assert.Equal(0x300, header.Version); // filesize - 22, which happens to be the size (22) of a PLACEABLEMETAHEADER struct Assert.Equal(3474, header.MetafileSize); Assert.Equal(-30, header.Bounds.X); Assert.Equal(-40, header.Bounds.Y); Assert.Equal(3096, header.Bounds.Width); Assert.Equal(4127, header.Bounds.Height); Assert.Equal(606, header.DpiX); Assert.Equal(606, header.DpiY); Assert.Equal(0, header.EmfPlusHeaderSize); Assert.Equal(0, header.LogicalDpiX); Assert.Equal(0, header.LogicalDpiY); Assert.NotNull(header.WmfHeader); Check_MetaHeader_WmfPlaceable(header.WmfHeader); Assert.False(header.IsDisplay()); Assert.False(header.IsEmf()); Assert.False(header.IsEmfOrEmfPlus()); Assert.False(header.IsEmfPlus()); Assert.False(header.IsEmfPlusDual()); Assert.False(header.IsEmfPlusOnly()); Assert.True(header.IsWmf()); Assert.True(header.IsWmfPlaceable()); } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFile_WmfPlaceable() { using (Metafile mf = new Metafile(Helpers.GetTestBitmapPath(WmfPlaceable))) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_WmfPlaceable(header1); MetaHeader mh1 = header1.WmfHeader; Check_MetaHeader_WmfPlaceable(mh1); MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader; Assert.NotSame(mh1, mh2); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFileStream_WmfPlaceable() { using (FileStream fs = File.OpenRead(Helpers.GetTestBitmapPath(WmfPlaceable))) using (Metafile mf = new Metafile(fs)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_WmfPlaceable(header1); MetaHeader mh1 = header1.WmfHeader; Check_MetaHeader_WmfPlaceable(mh1); MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader; Assert.NotSame(mh1, mh2); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromMemoryStream_WmfPlaceable() { string filename = Helpers.GetTestBitmapPath(WmfPlaceable); using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filename))) using (Metafile mf = new Metafile(ms)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_WmfPlaceable(header1); MetaHeader mh1 = header1.WmfHeader; Check_MetaHeader_WmfPlaceable(mh1); MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader; Assert.NotSame(mh1, mh2); } } private static void Check_MetafileHeader_Emf(MetafileHeader header) { Assert.Equal(MetafileType.Emf, header.Type); Assert.Equal(65536, header.Version); // extactly the filesize Assert.Equal(20456, header.MetafileSize); Assert.Equal(0, header.Bounds.X); Assert.Equal(0, header.Bounds.Y); Assert.Throws<ArgumentException>(() => header.WmfHeader); Assert.False(header.IsDisplay()); Assert.True(header.IsEmf()); Assert.True(header.IsEmfOrEmfPlus()); Assert.False(header.IsEmfPlus()); Assert.False(header.IsEmfPlusDual()); Assert.False(header.IsEmfPlusOnly()); Assert.False(header.IsWmf()); Assert.False(header.IsWmfPlaceable()); } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFile_Emf() { using (Metafile mf = new Metafile(Helpers.GetTestBitmapPath(Emf))) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_Emf(header1); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFileStream_Emf() { using (FileStream fs = File.OpenRead(Helpers.GetTestBitmapPath(Emf))) using (Metafile mf = new Metafile(fs)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_Emf(header1); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromMemoryStream_Emf() { string filename = Helpers.GetTestBitmapPath(Emf); using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filename))) using (Metafile mf = new Metafile(ms)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_Emf(header1); } } } [ActiveIssue("https://github.com/dotnet/runtime/issues/34591", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public class MetafileFulltrustTest { private void CheckEmptyHeader(Metafile mf, EmfType type) { MetafileHeader mh = mf.GetMetafileHeader(); Assert.Equal(0, mh.Bounds.X); Assert.Equal(0, mh.Bounds.Y); Assert.Equal(0, mh.Bounds.Width); Assert.Equal(0, mh.Bounds.Height); Assert.Equal(0, mh.MetafileSize); switch (type) { case EmfType.EmfOnly: Assert.Equal(MetafileType.Emf, mh.Type); break; case EmfType.EmfPlusDual: Assert.Equal(MetafileType.EmfPlusDual, mh.Type); break; case EmfType.EmfPlusOnly: Assert.Equal(MetafileType.EmfPlusOnly, mh.Type); break; default: Assert.True(false, string.Format("Unknown EmfType '{0}'", type)); break; } } private void Metafile_IntPtrEmfType(EmfType type) { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(hdc, type); CheckEmptyHeader(mf, type); } finally { g.ReleaseHdc(hdc); } } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_IntPtrRectangle_Empty() { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(hdc, new Rectangle()); CheckEmptyHeader(mf, EmfType.EmfPlusDual); } finally { g.ReleaseHdc(hdc); } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_IntPtrRectangleF_Empty() { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(hdc, new RectangleF()); CheckEmptyHeader(mf, EmfType.EmfPlusDual); } finally { g.ReleaseHdc(hdc); } } } private void Metafile_StreamEmfType(Stream stream, EmfType type) { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(stream, hdc, type); CheckEmptyHeader(mf, type); } finally { g.ReleaseHdc(hdc); } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_StreamIntPtrEmfType_Null() { Assert.Throws<NullReferenceException>(() => Metafile_StreamEmfType(null, EmfType.EmfOnly)); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_StreamIntPtrEmfType_EmfOnly() { using (MemoryStream ms = new MemoryStream()) { Metafile_StreamEmfType(ms, EmfType.EmfOnly); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_StreamIntPtrEmfType_Invalid() { using (MemoryStream ms = new MemoryStream()) { Assert.Throws<ArgumentException>(() => Metafile_StreamEmfType(ms, (EmfType)int.MinValue)); } } private void CreateFilename(EmfType type, bool single) { string name = string.Format("{0}-{1}.emf", type, single ? "Single" : "Multiple"); string filename = Path.Combine(Path.GetTempPath(), name); Metafile mf; using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { mf = new Metafile(filename, hdc, type); Assert.Equal(0, new FileInfo(filename).Length); } finally { g.ReleaseHdc(hdc); } } long size = 0; using (Graphics g = Graphics.FromImage(mf)) { g.FillRectangle(Brushes.BlueViolet, 10, 10, 80, 80); size = new FileInfo(filename).Length; Assert.Equal(0, size); } if (!single) { using (Graphics g = Graphics.FromImage(mf)) { g.DrawRectangle(Pens.Azure, 10, 10, 80, 80); } } mf.Dispose(); Assert.Equal(size, new FileInfo(filename).Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Measure() { Font test_font = new Font(FontFamily.GenericMonospace, 12); Metafile mf; using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { mf = new Metafile(hdc, EmfType.EmfPlusOnly); } finally { g.ReleaseHdc(hdc); } } using (Graphics g = Graphics.FromImage(mf)) { string text = "this\nis a test"; CharacterRange[] ranges = new CharacterRange[2]; ranges[0] = new CharacterRange(0, 5); ranges[1] = new CharacterRange(5, 9); SizeF size = g.MeasureString(text, test_font); Assert.False(size.IsEmpty); StringFormat sf = new StringFormat(); sf.FormatFlags = StringFormatFlags.NoClip; sf.SetMeasurableCharacterRanges(ranges); RectangleF rect = new RectangleF(0, 0, size.Width, size.Height); Region[] region = g.MeasureCharacterRanges(text, test_font, rect, sf); Assert.Equal(2, region.Length); mf.Dispose(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void WorldTransforms() { Metafile mf; using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { mf = new Metafile(hdc, EmfType.EmfPlusOnly); } finally { g.ReleaseHdc(hdc); } } using (Graphics g = Graphics.FromImage(mf)) { Assert.True(g.Transform.IsIdentity); g.ScaleTransform(2f, 0.5f); Assert.False(g.Transform.IsIdentity); g.RotateTransform(90); g.TranslateTransform(-2, 2); Matrix m = g.Transform; g.MultiplyTransform(m); // check float[] elements = g.Transform.Elements; Assert.Equal(-1.0, elements[0], 5); Assert.Equal(0.0, elements[1], 5); Assert.Equal(0.0, elements[2], 5); Assert.Equal(-1.0, elements[3], 5); Assert.Equal(-2.0, elements[4], 5); Assert.Equal(-3.0, elements[5], 5); g.Transform = m; elements = g.Transform.Elements; Assert.Equal(0.0, elements[0], 5); Assert.Equal(0.5, elements[1], 5); Assert.Equal(-2.0, elements[2], 5); Assert.Equal(0.0, elements[3], 5); Assert.Equal(-4.0, elements[4], 5); Assert.Equal(-1.0, elements[5], 5); g.ResetTransform(); Assert.True(g.Transform.IsIdentity); } mf.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // Metafile class unit tests // // Authors: // Sebastien Pouliot <[email protected]> // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // 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. // using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace MonoTests.System.Drawing.Imaging { [ActiveIssue("https://github.com/dotnet/runtime/issues/34591", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public class MetafileTest { public const string Bitmap = "non-inverted.bmp"; public const string WmfPlaceable = "telescope_01.wmf"; public const string Emf = "milkmateya01.emf"; [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_String() { string filename = Helpers.GetTestBitmapPath(WmfPlaceable); using (Metafile mf = new Metafile(filename)) using (Metafile clone = (Metafile)mf.Clone()) { } } private static void Check_MetaHeader_WmfPlaceable(MetaHeader mh) { Assert.Equal(9, mh.HeaderSize); Assert.Equal(98, mh.MaxRecord); Assert.Equal(3, mh.NoObjects); Assert.Equal(0, mh.NoParameters); Assert.Equal(1737, mh.Size); Assert.Equal(1, mh.Type); Assert.Equal(0x300, mh.Version); } private static void Check_MetafileHeader_WmfPlaceable(MetafileHeader header) { Assert.Equal(MetafileType.WmfPlaceable, header.Type); Assert.Equal(0x300, header.Version); // filesize - 22, which happens to be the size (22) of a PLACEABLEMETAHEADER struct Assert.Equal(3474, header.MetafileSize); Assert.Equal(-30, header.Bounds.X); Assert.Equal(-40, header.Bounds.Y); Assert.Equal(3096, header.Bounds.Width); Assert.Equal(4127, header.Bounds.Height); Assert.Equal(606, header.DpiX); Assert.Equal(606, header.DpiY); Assert.Equal(0, header.EmfPlusHeaderSize); Assert.Equal(0, header.LogicalDpiX); Assert.Equal(0, header.LogicalDpiY); Assert.NotNull(header.WmfHeader); Check_MetaHeader_WmfPlaceable(header.WmfHeader); Assert.False(header.IsDisplay()); Assert.False(header.IsEmf()); Assert.False(header.IsEmfOrEmfPlus()); Assert.False(header.IsEmfPlus()); Assert.False(header.IsEmfPlusDual()); Assert.False(header.IsEmfPlusOnly()); Assert.True(header.IsWmf()); Assert.True(header.IsWmfPlaceable()); } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFile_WmfPlaceable() { using (Metafile mf = new Metafile(Helpers.GetTestBitmapPath(WmfPlaceable))) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_WmfPlaceable(header1); MetaHeader mh1 = header1.WmfHeader; Check_MetaHeader_WmfPlaceable(mh1); MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader; Assert.NotSame(mh1, mh2); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFileStream_WmfPlaceable() { using (FileStream fs = File.OpenRead(Helpers.GetTestBitmapPath(WmfPlaceable))) using (Metafile mf = new Metafile(fs)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_WmfPlaceable(header1); MetaHeader mh1 = header1.WmfHeader; Check_MetaHeader_WmfPlaceable(mh1); MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader; Assert.NotSame(mh1, mh2); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromMemoryStream_WmfPlaceable() { string filename = Helpers.GetTestBitmapPath(WmfPlaceable); using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filename))) using (Metafile mf = new Metafile(ms)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_WmfPlaceable(header1); MetaHeader mh1 = header1.WmfHeader; Check_MetaHeader_WmfPlaceable(mh1); MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader; Assert.NotSame(mh1, mh2); } } private static void Check_MetafileHeader_Emf(MetafileHeader header) { Assert.Equal(MetafileType.Emf, header.Type); Assert.Equal(65536, header.Version); // extactly the filesize Assert.Equal(20456, header.MetafileSize); Assert.Equal(0, header.Bounds.X); Assert.Equal(0, header.Bounds.Y); Assert.Throws<ArgumentException>(() => header.WmfHeader); Assert.False(header.IsDisplay()); Assert.True(header.IsEmf()); Assert.True(header.IsEmfOrEmfPlus()); Assert.False(header.IsEmfPlus()); Assert.False(header.IsEmfPlusDual()); Assert.False(header.IsEmfPlusOnly()); Assert.False(header.IsWmf()); Assert.False(header.IsWmfPlaceable()); } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFile_Emf() { using (Metafile mf = new Metafile(Helpers.GetTestBitmapPath(Emf))) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_Emf(header1); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromFileStream_Emf() { using (FileStream fs = File.OpenRead(Helpers.GetTestBitmapPath(Emf))) using (Metafile mf = new Metafile(fs)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_Emf(header1); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetMetafileHeader_FromMemoryStream_Emf() { string filename = Helpers.GetTestBitmapPath(Emf); using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filename))) using (Metafile mf = new Metafile(ms)) { MetafileHeader header1 = mf.GetMetafileHeader(); Check_MetafileHeader_Emf(header1); } } } [ActiveIssue("https://github.com/dotnet/runtime/issues/34591", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public class MetafileFulltrustTest { private void CheckEmptyHeader(Metafile mf, EmfType type) { MetafileHeader mh = mf.GetMetafileHeader(); Assert.Equal(0, mh.Bounds.X); Assert.Equal(0, mh.Bounds.Y); Assert.Equal(0, mh.Bounds.Width); Assert.Equal(0, mh.Bounds.Height); Assert.Equal(0, mh.MetafileSize); switch (type) { case EmfType.EmfOnly: Assert.Equal(MetafileType.Emf, mh.Type); break; case EmfType.EmfPlusDual: Assert.Equal(MetafileType.EmfPlusDual, mh.Type); break; case EmfType.EmfPlusOnly: Assert.Equal(MetafileType.EmfPlusOnly, mh.Type); break; default: Assert.True(false, string.Format("Unknown EmfType '{0}'", type)); break; } } private void Metafile_IntPtrEmfType(EmfType type) { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(hdc, type); CheckEmptyHeader(mf, type); } finally { g.ReleaseHdc(hdc); } } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_IntPtrRectangle_Empty() { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(hdc, new Rectangle()); CheckEmptyHeader(mf, EmfType.EmfPlusDual); } finally { g.ReleaseHdc(hdc); } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_IntPtrRectangleF_Empty() { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(hdc, new RectangleF()); CheckEmptyHeader(mf, EmfType.EmfPlusDual); } finally { g.ReleaseHdc(hdc); } } } private void Metafile_StreamEmfType(Stream stream, EmfType type) { using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { Metafile mf = new Metafile(stream, hdc, type); CheckEmptyHeader(mf, type); } finally { g.ReleaseHdc(hdc); } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_StreamIntPtrEmfType_Null() { Assert.Throws<NullReferenceException>(() => Metafile_StreamEmfType(null, EmfType.EmfOnly)); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_StreamIntPtrEmfType_EmfOnly() { using (MemoryStream ms = new MemoryStream()) { Metafile_StreamEmfType(ms, EmfType.EmfOnly); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Metafile_StreamIntPtrEmfType_Invalid() { using (MemoryStream ms = new MemoryStream()) { Assert.Throws<ArgumentException>(() => Metafile_StreamEmfType(ms, (EmfType)int.MinValue)); } } private void CreateFilename(EmfType type, bool single) { string name = string.Format("{0}-{1}.emf", type, single ? "Single" : "Multiple"); string filename = Path.Combine(Path.GetTempPath(), name); Metafile mf; using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { mf = new Metafile(filename, hdc, type); Assert.Equal(0, new FileInfo(filename).Length); } finally { g.ReleaseHdc(hdc); } } long size = 0; using (Graphics g = Graphics.FromImage(mf)) { g.FillRectangle(Brushes.BlueViolet, 10, 10, 80, 80); size = new FileInfo(filename).Length; Assert.Equal(0, size); } if (!single) { using (Graphics g = Graphics.FromImage(mf)) { g.DrawRectangle(Pens.Azure, 10, 10, 80, 80); } } mf.Dispose(); Assert.Equal(size, new FileInfo(filename).Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Measure() { Font test_font = new Font(FontFamily.GenericMonospace, 12); Metafile mf; using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { mf = new Metafile(hdc, EmfType.EmfPlusOnly); } finally { g.ReleaseHdc(hdc); } } using (Graphics g = Graphics.FromImage(mf)) { string text = "this\nis a test"; CharacterRange[] ranges = new CharacterRange[2]; ranges[0] = new CharacterRange(0, 5); ranges[1] = new CharacterRange(5, 9); SizeF size = g.MeasureString(text, test_font); Assert.False(size.IsEmpty); StringFormat sf = new StringFormat(); sf.FormatFlags = StringFormatFlags.NoClip; sf.SetMeasurableCharacterRanges(ranges); RectangleF rect = new RectangleF(0, 0, size.Width, size.Height); Region[] region = g.MeasureCharacterRanges(text, test_font, rect, sf); Assert.Equal(2, region.Length); mf.Dispose(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void WorldTransforms() { Metafile mf; using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bmp)) { IntPtr hdc = g.GetHdc(); try { mf = new Metafile(hdc, EmfType.EmfPlusOnly); } finally { g.ReleaseHdc(hdc); } } using (Graphics g = Graphics.FromImage(mf)) { Assert.True(g.Transform.IsIdentity); g.ScaleTransform(2f, 0.5f); Assert.False(g.Transform.IsIdentity); g.RotateTransform(90); g.TranslateTransform(-2, 2); Matrix m = g.Transform; g.MultiplyTransform(m); // check float[] elements = g.Transform.Elements; Assert.Equal(-1.0, elements[0], 5); Assert.Equal(0.0, elements[1], 5); Assert.Equal(0.0, elements[2], 5); Assert.Equal(-1.0, elements[3], 5); Assert.Equal(-2.0, elements[4], 5); Assert.Equal(-3.0, elements[5], 5); g.Transform = m; elements = g.Transform.Elements; Assert.Equal(0.0, elements[0], 5); Assert.Equal(0.5, elements[1], 5); Assert.Equal(-2.0, elements[2], 5); Assert.Equal(0.0, elements[3], 5); Assert.Equal(-4.0, elements[4], 5); Assert.Equal(-1.0, elements[5], 5); g.ResetTransform(); Assert.True(g.Transform.IsIdentity); } mf.Dispose(); } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Generics/Arrays/ConstructedTypes/Jagged/class01_instance.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; public struct ValX1<T> { public T t; public ValX1(T t) { this.t = t; } } public class RefX1<T> { public T t; public RefX1(T t) { this.t = t; } } public class Gen<T> { public T Fld1; public Gen(T fld1) { Fld1 = fld1; } } public class ArrayHolder { public Gen<int>[][][][][] GenArray = new Gen<int>[10][][][][]; } public class Test_class01_instance { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { int size = 10; int i, j, k, l, m; double sum = 0; ArrayHolder ArrayHolderInst = new ArrayHolder(); for (i = 0; i < size; i++) { ArrayHolderInst.GenArray[i] = new Gen<int>[i][][][]; for (j = 0; j < i; j++) { ArrayHolderInst.GenArray[i][j] = new Gen<int>[j][][]; for (k = 0; k < j; k++) { ArrayHolderInst.GenArray[i][j][k] = new Gen<int>[k][]; for (l = 0; l < k; l++) { ArrayHolderInst.GenArray[i][j][k][l] = new Gen<int>[l]; for (m = 0; m < l; m++) { ArrayHolderInst.GenArray[i][j][k][l][m] = new Gen<int>(i * j * k * l * m); } } } } } for (i = 0; i < size; i++) { for (j = 0; j < i; j++) { for (k = 0; k < j; k++) { for (l = 0; l < k; l++) { for (m = 0; m < l; m++) { sum += ArrayHolderInst.GenArray[i][j][k][l][m].Fld1; } } } } } Eval(sum == 269325); sum = 0; if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; public struct ValX1<T> { public T t; public ValX1(T t) { this.t = t; } } public class RefX1<T> { public T t; public RefX1(T t) { this.t = t; } } public class Gen<T> { public T Fld1; public Gen(T fld1) { Fld1 = fld1; } } public class ArrayHolder { public Gen<int>[][][][][] GenArray = new Gen<int>[10][][][][]; } public class Test_class01_instance { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { int size = 10; int i, j, k, l, m; double sum = 0; ArrayHolder ArrayHolderInst = new ArrayHolder(); for (i = 0; i < size; i++) { ArrayHolderInst.GenArray[i] = new Gen<int>[i][][][]; for (j = 0; j < i; j++) { ArrayHolderInst.GenArray[i][j] = new Gen<int>[j][][]; for (k = 0; k < j; k++) { ArrayHolderInst.GenArray[i][j][k] = new Gen<int>[k][]; for (l = 0; l < k; l++) { ArrayHolderInst.GenArray[i][j][k][l] = new Gen<int>[l]; for (m = 0; m < l; m++) { ArrayHolderInst.GenArray[i][j][k][l][m] = new Gen<int>(i * j * k * l * m); } } } } } for (i = 0; i < size; i++) { for (j = 0; j < i; j++) { for (k = 0; k < j; k++) { for (l = 0; l < k; l++) { for (m = 0; m < l; m++) { sum += ArrayHolderInst.GenArray[i][j][k][l][m].Fld1; } } } } } Eval(sum == 269325); sum = 0; if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/null/box-unbox-null029.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of NotEmptyStructConstrainedGenA<int> using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructConstrainedGenA<int>?)o) == null; } private static int Main() { NotEmptyStructConstrainedGenA<int>? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of NotEmptyStructConstrainedGenA<int> using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NotEmptyStructConstrainedGenA<int>?)o) == null; } private static int Main() { NotEmptyStructConstrainedGenA<int>? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.IO.Ports/tests/Support/SerialPortProperties.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.IO.Ports; using System.Reflection; using System.Text; using Xunit; namespace Legacy.Support { public class SerialPortProperties { // All of the following properties are the defualts of SerialPort when the // just the default constructor has been called. The names of the data members here must // begin with default followed by the EXACT(case sensitive) name of // the property in SerialPort class. If a default for a property is not set // here then the property can never be set in this class and will never be // used for verification. private const int defaultBaudRate = 9600; public static readonly string defaultPortName = "COM1"; private const int defaultDataBits = 8; public static readonly StopBits defaultStopBits = StopBits.One; public static readonly Parity defaultParity = Parity.None; public static readonly Handshake defaultHandshake = Handshake.None; public static readonly Encoding defaultEncoding = new ASCIIEncoding(); public static readonly bool defaultDtrEnable = false; public static readonly bool defaultRtsEnable = false; private const int defaultReadTimeout = -1; private const int defaultWriteTimeout = -1; public static readonly Type defaultBytesToRead = typeof(InvalidOperationException); public static readonly Type defaultBytesToWrite = typeof(InvalidOperationException); public static readonly bool defaultIsOpen = false; public static readonly Type defaultBaseStream = typeof(InvalidOperationException); private const int defaultReceivedBytesThreshold = 1; public static readonly bool defaultDiscardNull = false; public static readonly byte defaultParityReplace = (byte)'?'; public static readonly Type defaultCDHolding = typeof(InvalidOperationException); public static readonly Type defaultCtsHolding = typeof(InvalidOperationException); public static readonly Type defaultDsrHolding = typeof(InvalidOperationException); public static readonly string defaultNewLine = "\n"; public static readonly Type defaultBreakState = typeof(InvalidOperationException); private const int defaultReadBufferSize = 4 * 1024; private const int defaultWriteBufferSize = 2 * 1024; // All of the following properties are the defualts of SerialPort when the // serial port connection is open. The names of the data members here must // begin with openDefault followed by the EXACT(case sensitive) name of // the property in SerialPort class. private const int openDefaultBaudRate = 9600; public static readonly string openDefaultPortName = "COM1"; private const int openDefaultDataBits = 8; public static readonly StopBits openDefaultStopBits = StopBits.One; public static readonly Parity openDefaultParity = Parity.None; public static readonly Handshake openDefaultHandshake = Handshake.None; public static readonly Encoding openDefaultEncoding = new ASCIIEncoding(); public static readonly bool openDefaultDtrEnable = false; public static readonly bool openDefaultRtsEnable = false; private const int openDefaultReadTimeout = -1; private const int openDefaultWriteTimeout = -1; private const int openDefaultBytesToRead = 0; private const int openDefaultBytesToWrite = 0; public static readonly bool openDefaultIsOpen = true; private const int openDefaultReceivedBytesThreshold = 1; public static readonly bool openDefaultDiscardNull = false; public static readonly byte openDefaultParityReplace = (byte)'?'; // Removing the following properties from default checks. Sometimes these can be true (as read from the GetCommModemStatus win32 API) // which causes test failures. Since these are read-only properties and are simply obtained from a bitfield, there is a very low probability // of regression involving these properties. // // public static readonly bool openDefaultCDHolding = false; // public static readonly bool openDefaultCtsHolding = false; // public static readonly bool openDefaultDsrHolding = false; public static readonly string openDefaultNewLine = "\n"; public static readonly bool openDefaultBreakState = false; private const int openReadBufferSize = 4 * 1024; private const int openWriteBufferSize = 2 * 1024; private Hashtable _properties; private Hashtable _openDefaultProperties; private Hashtable _defaultProperties; public SerialPortProperties() { _properties = new Hashtable(); _openDefaultProperties = new Hashtable(); _defaultProperties = new Hashtable(); LoadDefaults(); } public object GetDefualtOpenProperty(string name) { return _openDefaultProperties[name]; } public object GetDefualtProperty(string name) { return _defaultProperties[name]; } public object GetProperty(string name) { return _properties[name]; } public void SetAllPropertiesToOpenDefaults() { SetAllPropertiesToDefaults(_openDefaultProperties); } public void SetAllPropertiesToDefaults() { SetAllPropertiesToDefaults(_defaultProperties); } public object SetopenDefaultProperty(string name) { return SetDefaultProperty(name, _openDefaultProperties); } public object SetdefaultProperty(string name) { return SetDefaultProperty(name, _defaultProperties); } public object SetProperty(string name, object value) { object retVal = null; if (null != _openDefaultProperties[name]) { retVal = _properties[name]; _properties[name] = value; } return retVal; } public override string ToString() { StringBuilder strBuf = new StringBuilder(); foreach (object key in _properties.Keys) { strBuf.Append(key + "=" + _properties[key] + "\n"); } return strBuf.ToString(); } public Hashtable VerifyProperties(SerialPort port) { Type serialPortType = typeof(SerialPort); Hashtable badProps = new Hashtable(); // If we could not get the type of SerialPort then verification can not // occur and we should throw an exception if (null == serialPortType) { throw new Exception("Could not create a Type object of SerialPort"); } // For each key in the properties Hashtable verify that the property in the // SerialPort Object port with the same name as the key has the same value as // the value corresponding to the key in the HashTable. If the port is in a // state where accessing a property is suppose to throw an exception this can be // verified by setting the value in the hashtable to the System.Type of the // expected exception foreach (object key in _properties.Keys) { object value = _properties[key]; try { PropertyInfo serialPortProperty = serialPortType.GetProperty((string)key); object serialPortValue; if ((string)key == "RtsEnable" && ((port.Handshake == Handshake.RequestToSend && (Handshake)_properties["Handshake"] == Handshake.RequestToSend) || (port.Handshake == Handshake.RequestToSendXOnXOff && (Handshake)_properties["Handshake"] == Handshake.RequestToSendXOnXOff))) { continue; } serialPortValue = serialPortProperty.GetValue(port, null); if (value == null) { if (value != serialPortValue) { badProps[key] = serialPortValue; } } else if (!value.Equals(serialPortValue)) { badProps[key] = serialPortValue; } } catch (Exception e) { // An exception was thrown while retrieving the value of the property in // the SerialPort object. However this may be the exepected operation of // SerialPort so the type of the exception must be verified. Reflection // throws it's own exception ontop of SerialPorts so we must use the // InnerException of the own that Reflection throws if (null != e.InnerException) { if (null == value || !value.Equals(e.InnerException.GetType())) { badProps[key] = e.GetType(); } } else { badProps[key] = e.GetType(); } } } if (0 == badProps.Count) { return null; } else { return badProps; } } public void VerifyPropertiesAndPrint(SerialPort port) { Hashtable badProps; if (null == (badProps = VerifyProperties(port))) { // SerialPort values correctly set return; } else { StringBuilder sb = new StringBuilder(); foreach (object key in badProps.Keys) { sb.AppendLine($"{key}={badProps[key]} expected {GetProperty((string)key)}"); } Assert.True(false, sb.ToString()); } } private void LoadDefaults() { LoadFields("openDefault", _openDefaultProperties); LoadFields("default", _defaultProperties); } private void LoadFields(string startsWith, Hashtable fields) { Type serialPropertiesType = typeof(SerialPortProperties); // For each field in this class that starts with the string startsWith create // a key value pair in the hashtable fields with key being the rest of the // field name after startsWith and the value is whatever the value is of the field // in this class foreach (FieldInfo defaultField in serialPropertiesType.GetFields()) { string defaultFieldName = defaultField.Name; if (0 == defaultFieldName.IndexOf(startsWith)) { string fieldName = defaultFieldName.Replace(startsWith, ""); object defaultValue = defaultField.GetValue(this); fields[fieldName] = defaultValue; } } } private void SetAllPropertiesToDefaults(Hashtable defaultProperties) { _properties.Clear(); // For each key in the defaultProperties Hashtable set poperties[key] // with the corresponding value in defaultProperties foreach (object key in defaultProperties.Keys) { _properties[key] = defaultProperties[key]; } } private object SetDefaultProperty(string name, Hashtable defaultProperties) { object retVal = null; // Only Set the default value if it exists in the defaultProperties Hashtable // This will prevent the ability to create arbitrary keys(Property names) if (null != defaultProperties[name]) { retVal = _properties[name]; _properties[name] = defaultProperties[name]; } return retVal; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.IO.Ports; using System.Reflection; using System.Text; using Xunit; namespace Legacy.Support { public class SerialPortProperties { // All of the following properties are the defualts of SerialPort when the // just the default constructor has been called. The names of the data members here must // begin with default followed by the EXACT(case sensitive) name of // the property in SerialPort class. If a default for a property is not set // here then the property can never be set in this class and will never be // used for verification. private const int defaultBaudRate = 9600; public static readonly string defaultPortName = "COM1"; private const int defaultDataBits = 8; public static readonly StopBits defaultStopBits = StopBits.One; public static readonly Parity defaultParity = Parity.None; public static readonly Handshake defaultHandshake = Handshake.None; public static readonly Encoding defaultEncoding = new ASCIIEncoding(); public static readonly bool defaultDtrEnable = false; public static readonly bool defaultRtsEnable = false; private const int defaultReadTimeout = -1; private const int defaultWriteTimeout = -1; public static readonly Type defaultBytesToRead = typeof(InvalidOperationException); public static readonly Type defaultBytesToWrite = typeof(InvalidOperationException); public static readonly bool defaultIsOpen = false; public static readonly Type defaultBaseStream = typeof(InvalidOperationException); private const int defaultReceivedBytesThreshold = 1; public static readonly bool defaultDiscardNull = false; public static readonly byte defaultParityReplace = (byte)'?'; public static readonly Type defaultCDHolding = typeof(InvalidOperationException); public static readonly Type defaultCtsHolding = typeof(InvalidOperationException); public static readonly Type defaultDsrHolding = typeof(InvalidOperationException); public static readonly string defaultNewLine = "\n"; public static readonly Type defaultBreakState = typeof(InvalidOperationException); private const int defaultReadBufferSize = 4 * 1024; private const int defaultWriteBufferSize = 2 * 1024; // All of the following properties are the defualts of SerialPort when the // serial port connection is open. The names of the data members here must // begin with openDefault followed by the EXACT(case sensitive) name of // the property in SerialPort class. private const int openDefaultBaudRate = 9600; public static readonly string openDefaultPortName = "COM1"; private const int openDefaultDataBits = 8; public static readonly StopBits openDefaultStopBits = StopBits.One; public static readonly Parity openDefaultParity = Parity.None; public static readonly Handshake openDefaultHandshake = Handshake.None; public static readonly Encoding openDefaultEncoding = new ASCIIEncoding(); public static readonly bool openDefaultDtrEnable = false; public static readonly bool openDefaultRtsEnable = false; private const int openDefaultReadTimeout = -1; private const int openDefaultWriteTimeout = -1; private const int openDefaultBytesToRead = 0; private const int openDefaultBytesToWrite = 0; public static readonly bool openDefaultIsOpen = true; private const int openDefaultReceivedBytesThreshold = 1; public static readonly bool openDefaultDiscardNull = false; public static readonly byte openDefaultParityReplace = (byte)'?'; // Removing the following properties from default checks. Sometimes these can be true (as read from the GetCommModemStatus win32 API) // which causes test failures. Since these are read-only properties and are simply obtained from a bitfield, there is a very low probability // of regression involving these properties. // // public static readonly bool openDefaultCDHolding = false; // public static readonly bool openDefaultCtsHolding = false; // public static readonly bool openDefaultDsrHolding = false; public static readonly string openDefaultNewLine = "\n"; public static readonly bool openDefaultBreakState = false; private const int openReadBufferSize = 4 * 1024; private const int openWriteBufferSize = 2 * 1024; private Hashtable _properties; private Hashtable _openDefaultProperties; private Hashtable _defaultProperties; public SerialPortProperties() { _properties = new Hashtable(); _openDefaultProperties = new Hashtable(); _defaultProperties = new Hashtable(); LoadDefaults(); } public object GetDefualtOpenProperty(string name) { return _openDefaultProperties[name]; } public object GetDefualtProperty(string name) { return _defaultProperties[name]; } public object GetProperty(string name) { return _properties[name]; } public void SetAllPropertiesToOpenDefaults() { SetAllPropertiesToDefaults(_openDefaultProperties); } public void SetAllPropertiesToDefaults() { SetAllPropertiesToDefaults(_defaultProperties); } public object SetopenDefaultProperty(string name) { return SetDefaultProperty(name, _openDefaultProperties); } public object SetdefaultProperty(string name) { return SetDefaultProperty(name, _defaultProperties); } public object SetProperty(string name, object value) { object retVal = null; if (null != _openDefaultProperties[name]) { retVal = _properties[name]; _properties[name] = value; } return retVal; } public override string ToString() { StringBuilder strBuf = new StringBuilder(); foreach (object key in _properties.Keys) { strBuf.Append(key + "=" + _properties[key] + "\n"); } return strBuf.ToString(); } public Hashtable VerifyProperties(SerialPort port) { Type serialPortType = typeof(SerialPort); Hashtable badProps = new Hashtable(); // If we could not get the type of SerialPort then verification can not // occur and we should throw an exception if (null == serialPortType) { throw new Exception("Could not create a Type object of SerialPort"); } // For each key in the properties Hashtable verify that the property in the // SerialPort Object port with the same name as the key has the same value as // the value corresponding to the key in the HashTable. If the port is in a // state where accessing a property is suppose to throw an exception this can be // verified by setting the value in the hashtable to the System.Type of the // expected exception foreach (object key in _properties.Keys) { object value = _properties[key]; try { PropertyInfo serialPortProperty = serialPortType.GetProperty((string)key); object serialPortValue; if ((string)key == "RtsEnable" && ((port.Handshake == Handshake.RequestToSend && (Handshake)_properties["Handshake"] == Handshake.RequestToSend) || (port.Handshake == Handshake.RequestToSendXOnXOff && (Handshake)_properties["Handshake"] == Handshake.RequestToSendXOnXOff))) { continue; } serialPortValue = serialPortProperty.GetValue(port, null); if (value == null) { if (value != serialPortValue) { badProps[key] = serialPortValue; } } else if (!value.Equals(serialPortValue)) { badProps[key] = serialPortValue; } } catch (Exception e) { // An exception was thrown while retrieving the value of the property in // the SerialPort object. However this may be the exepected operation of // SerialPort so the type of the exception must be verified. Reflection // throws it's own exception ontop of SerialPorts so we must use the // InnerException of the own that Reflection throws if (null != e.InnerException) { if (null == value || !value.Equals(e.InnerException.GetType())) { badProps[key] = e.GetType(); } } else { badProps[key] = e.GetType(); } } } if (0 == badProps.Count) { return null; } else { return badProps; } } public void VerifyPropertiesAndPrint(SerialPort port) { Hashtable badProps; if (null == (badProps = VerifyProperties(port))) { // SerialPort values correctly set return; } else { StringBuilder sb = new StringBuilder(); foreach (object key in badProps.Keys) { sb.AppendLine($"{key}={badProps[key]} expected {GetProperty((string)key)}"); } Assert.True(false, sb.ToString()); } } private void LoadDefaults() { LoadFields("openDefault", _openDefaultProperties); LoadFields("default", _defaultProperties); } private void LoadFields(string startsWith, Hashtable fields) { Type serialPropertiesType = typeof(SerialPortProperties); // For each field in this class that starts with the string startsWith create // a key value pair in the hashtable fields with key being the rest of the // field name after startsWith and the value is whatever the value is of the field // in this class foreach (FieldInfo defaultField in serialPropertiesType.GetFields()) { string defaultFieldName = defaultField.Name; if (0 == defaultFieldName.IndexOf(startsWith)) { string fieldName = defaultFieldName.Replace(startsWith, ""); object defaultValue = defaultField.GetValue(this); fields[fieldName] = defaultValue; } } } private void SetAllPropertiesToDefaults(Hashtable defaultProperties) { _properties.Clear(); // For each key in the defaultProperties Hashtable set poperties[key] // with the corresponding value in defaultProperties foreach (object key in defaultProperties.Keys) { _properties[key] = defaultProperties[key]; } } private object SetDefaultProperty(string name, Hashtable defaultProperties) { object retVal = null; // Only Set the default value if it exists in the defaultProperties Hashtable // This will prevent the ability to create arbitrary keys(Property names) if (null != defaultProperties[name]) { retVal = _properties[name]; _properties[name] = defaultProperties[name]; } return retVal; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/mono/mono/tests/gc-oom-handling.cs
using System; using System.Collections.Generic; class Driver { static int Main () { Console.WriteLine ("start"); var l = new object[40000]; try { for (int i = 0; i < 40000; ++i) { var foo = new byte[2000]; l[i] = foo; } Console.WriteLine ("done"); return 1; } catch (Exception e) { /*Create massive fragmentation - hopefully*/ for (int i = 0; i < 40000; i += 2) l[i] = null; /*Fist major schedule the given block range for evacuation*/ GC.Collect (); /*Second major triggers evacuation*/ GC.Collect (); Array.Clear (l, 0, 40000); l = null; Console.WriteLine ("OOM done"); } return 0; } }
using System; using System.Collections.Generic; class Driver { static int Main () { Console.WriteLine ("start"); var l = new object[40000]; try { for (int i = 0; i < 40000; ++i) { var foo = new byte[2000]; l[i] = foo; } Console.WriteLine ("done"); return 1; } catch (Exception e) { /*Create massive fragmentation - hopefully*/ for (int i = 0; i < 40000; i += 2) l[i] = null; /*Fist major schedule the given block range for evacuation*/ GC.Collect (); /*Second major triggers evacuation*/ GC.Collect (); Array.Clear (l, 0, 40000); l = null; Console.WriteLine ("OOM done"); } return 0; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Common/tests/System/Runtime/Serialization/Utils.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.Concurrent; using System.Diagnostics; using System.IO; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using System.Linq; using System.Reflection; using System.Runtime.Loader; using Xunit; internal static class Utils { internal static void Equal<T>(T[] x, T[] y, Func<T, T, bool> f) { if (x == null) { Assert.Null(y); } else if (y == null) { Assert.Null(x); } else { Assert.True(x.Length == y.Length); for (int i = 0; i < x.Length; i++) { Assert.True(f(x[i], y[i])); } } } private static ConcurrentDictionary<string, string> s_prefixToNamespaceDesk = new ConcurrentDictionary<string, string>(); private static ConcurrentDictionary<string, string> s_prefixToNamespaceCoreCLR = new ConcurrentDictionary<string, string>(); internal struct CompareResult { public bool Equal { get; set; } public string ErrorMessage { get; set; } } internal static int Min(int a, int b) { if (a < b) { return a; } return b; } internal static int Max(int a, int b) { if (a > b) { return a; } return b; } private static CompareResult CompareString(string expected, string actual) { if (expected == null && actual == null) { return new CompareResult { Equal = true }; } if (expected == null) { return new CompareResult { ErrorMessage = "expected null, but actual was:\n" + actual }; } if (actual == null) { return new CompareResult { ErrorMessage = "actual was null, but was expecting:\n" + expected }; } int commonLength = Min(actual.Length, expected.Length); for (int currentIndex = 0; currentIndex < commonLength; ++currentIndex) { char expectedChar = expected[currentIndex]; char actualChar = actual[currentIndex]; if (expectedChar != actualChar) { int from = Max(currentIndex - 10, 0); int errPosition = currentIndex - from; int to = Min(currentIndex + 20, commonLength); string message = string.Format("strings differ at index {0}\n{3}\u2193\n[expected]:{1}\n[actual ]:{2}\n{3}\u2191\n[Expected (with length={4})]:\n{5}\n[Actual (with length={6})]:\n{7}", currentIndex, expected.Substring(from, to - from), actual.Substring(from, to - from), new string(' ', errPosition + " expected :".Length), expected.Length, expected, actual.Length, actual); return new CompareResult { ErrorMessage = message }; } } if (actual.Length != commonLength) { return new CompareResult { ErrorMessage = "actual is longer. The unwanted suffix is:\n" + actual.Substring(commonLength) }; } if (expected.Length != commonLength) { return new CompareResult { ErrorMessage = "expected is longer. The missing suffix is:\n" + expected.Substring(commonLength) }; } return new CompareResult { Equal = true }; } internal static CompareResult Compare(string expected, string actual, bool runSmartXmlComparerOnFailure = true) { // for CORECLR we get different xml hence we have updated code for smartyXMLcomparision CompareResult stringcompare = CompareString(expected, actual); if (runSmartXmlComparerOnFailure == true) { if ((stringcompare.Equal != true) && (!string.IsNullOrEmpty(stringcompare.ErrorMessage))) { Debug.WriteLine("Basic baseline XML comparison failed with the error : {0}\n. Running the smart XML comparer", stringcompare.ErrorMessage); if (!SmartXmlCompare(expected, actual)) { return new CompareResult { ErrorMessage = "XML comparison is also failing" }; } else { return new CompareResult { Equal = true }; } } } return stringcompare; } public static bool SmartXmlCompare(string expected, string actual) { XElement deskXElem = XElement.Parse(expected); XElement coreCLRXElem = XElement.Parse(actual); s_prefixToNamespaceDesk.Clear(); s_prefixToNamespaceCoreCLR.Clear(); return CompareXElements(deskXElem, coreCLRXElem); } private static bool CompareXElements(XElement baselineXElement, XElement actualXElement) { // Check whether the XName is the same, this can be done by comparing the two XNames. if (!baselineXElement.Name.Equals(actualXElement.Name)) { // Two nodes could be same even if their localName is not the same. // For example- // Desktop //<GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2zbP0weY4 xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/SerializationTypes"> // <genericData1 z:Id="i2"> // <BaseData></BaseData> // <DerivedData></DerivedData> // </genericData1> // <genericData2 z:Id="i3"> // <BaseData></BaseData> // <DerivedData></DerivedData> // </genericData2> //</GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2zbP0weY4> // vs CoreCLR. //<GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ z:Id="i1" xmlns="http://schemas.datacontract.org/2004/07/SerializationTypes" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"> // <genericData1 z:Id="i2"> // <BaseData /> // <DerivedData /> // </genericData1> // <genericData2 z:Id="i3"> // <BaseData /> // <DerivedData /> // </genericData2> //</GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ> // Note the incorrect padding in the end of GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ // The difference is MD5 hashcode applied to the Type.FullName and is because full typeName in .NET Framework and CoreCLR returns different value. // Hack for the above reason. int deskIdx, coreCLRIdx; if (-1 != (deskIdx = baselineXElement.Name.LocalName.IndexOf("zbP0weY4"))) { // Check if the CoreCLR string contains the other. if (-1 != (coreCLRIdx = actualXElement.Name.LocalName.IndexOf("RkuXKXCQ"))) { // Check whether the substring before this matches if (0 == string.Compare(baselineXElement.Name.LocalName.Substring(0, deskIdx), actualXElement.Name.LocalName.Substring(0, coreCLRIdx))) { // Check if the namespace matched. if (baselineXElement.Name.Namespace.Equals(actualXElement.Name.Namespace)) return true; } } } string message = string.Format("Namespace difference \n[expected]:{0}\n[actual ]:{1}\n Padding expected elements is {2}", baselineXElement.Name.Namespace, actualXElement.Name.Namespace, actualXElement.Name.LocalName ); Debug.WriteLine("Either padding is different or namespace is not matching.\n" + message); return false; } // Comparing attributes XAttribute[] deskAtrs = baselineXElement.Attributes().OrderBy(m => m.Value).ToArray(); XAttribute[] coreCLRAtrs = actualXElement.Attributes().OrderBy(m => m.Value).ToArray(); if (deskAtrs.Length != coreCLRAtrs.Length) { Debug.WriteLine("Number of attributes differ.Expected number of attributes are " + deskAtrs.Length.ToString() + " Actual number of attributes are " + coreCLRAtrs.Length.ToString()); return false; } // At this point the attributes should be all in the same order. for (int i = 0; i < deskAtrs.Length; i++) { if (deskAtrs[i].IsNamespaceDeclaration != coreCLRAtrs[i].IsNamespaceDeclaration) { Debug.WriteLine("Either expected attribute {0} is not namespace declaration or actual attribute {1}", deskAtrs[i].ToString(), coreCLRAtrs[i].ToString()); return false; } if (deskAtrs[i].IsNamespaceDeclaration) { if (0 != string.Compare(deskAtrs[i].Name.NamespaceName, coreCLRAtrs[i].Name.NamespaceName)) { Debug.WriteLine("Namespaces are different.Expected {0} namespace doesn't match with actual {1} namespace ", deskAtrs[i].Name.NamespaceName, coreCLRAtrs[i].Name.NamespaceName); return false; } if (0 != string.Compare(deskAtrs[i].Value, coreCLRAtrs[i].Value)) { Debug.WriteLine("Attribute values are different. Expected {0} attribute values doesn't match with actual {1} attribute value.", deskAtrs[i].Value, coreCLRAtrs[i].Value); return false; } // Update the dictionaries s_prefixToNamespaceDesk[deskAtrs[i].Name.LocalName] = deskAtrs[i].Value; s_prefixToNamespaceCoreCLR[coreCLRAtrs[i].Name.LocalName] = coreCLRAtrs[i].Value; } else { if (!deskAtrs[i].Name.Equals(coreCLRAtrs[i].Name)) { Debug.WriteLine("Attribute names are different. Expected name is {0} but actual name is {1}", deskAtrs[i].Name, coreCLRAtrs[i].Name); return false; } string deskPrefix, coreCLRPrefix; if (IsPrefixedAttributeValue(deskAtrs[i].Value, out deskPrefix)) { if (IsPrefixedAttributeValue(coreCLRAtrs[i].Value, out coreCLRPrefix)) { // Check if they both have the same namespace. XNamespace deskns = baselineXElement.GetNamespaceOfPrefix(deskPrefix); XNamespace coreclrns = actualXElement.GetNamespaceOfPrefix(coreCLRPrefix); if (!deskns.Equals(coreclrns)) { Debug.WriteLine("XML namespace of attribute is different. Expected is {0} but actual is {1}", deskns.NamespaceName, coreclrns.NamespaceName); return false; } // Update the dictionaries s_prefixToNamespaceDesk[deskPrefix] = deskns.NamespaceName; s_prefixToNamespaceCoreCLR[coreCLRPrefix] = coreclrns.NamespaceName; } else { Debug.WriteLine("Either expected {0} or actual {1} attribute value doesn't have prefix :", deskAtrs[i].Value, coreCLRAtrs[i].Value); return false; } } } } if (!CompareValue(baselineXElement.Value, actualXElement.Value)) return false; // Serialized values can only have XElement and XText and hence we do not traverse the complete node structures and only the descendants. XElement[] deskChildElems = baselineXElement.Descendants().OrderBy(m => m.Name.NamespaceName).ToArray(); XElement[] coreCLRChildElems = actualXElement.Descendants().OrderBy(m => m.Name.NamespaceName).ToArray(); if (deskChildElems.Length != coreCLRChildElems.Length) { return false; } for (int i = 0; i < deskChildElems.Length; i++) { if (!CompareXElements(deskChildElems[i], coreCLRChildElems[i])) return false; } // If we have reached here, XML is same. return true; } private static bool CompareValue(string deskElemValue, string coreCLRElemValue) { if (deskElemValue.Equals(coreCLRElemValue)) return true; // For text of the form // <z:QName xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:a="def">a:abc</z:QName> // In the above XML text the XElement.Value is a:abc which in CoreCLR could be something like d1p1:abc // and hence we value check will fail. // To mitigate this we store the namespaces from the parent XElement and use it to check the actual value. string deskPrefix, coreCLRPrefix; if (IsPrefixedAttributeValue(deskElemValue, out deskPrefix)) { if (IsPrefixedAttributeValue(coreCLRElemValue, out coreCLRPrefix)) { // Check whether the prefixes have the right namespaces attached. string deskNs, coreCLRNs; if (s_prefixToNamespaceDesk.TryGetValue(deskPrefix, out deskNs)) { if (s_prefixToNamespaceCoreCLR.TryGetValue(coreCLRPrefix, out coreCLRNs)) { if (deskNs.Equals(coreCLRNs)) { // Also we check that the rest of the strings match. if (0 == string.Compare(deskElemValue.Substring(deskPrefix.Length), coreCLRElemValue.Substring(coreCLRPrefix.Length))) return true; } } } } Debug.WriteLine("Attribute value {0} has empty prefix value before :", coreCLRElemValue); return false; } Debug.WriteLine("Attribute value {0} has empty prefix value before :", deskElemValue); return false; } private static bool IsPrefixedAttributeValue(string atrValue, out string localPrefix) { int prefixIndex = atrValue.IndexOf(":"); if (prefixIndex != -1) { localPrefix = atrValue.Substring(0, prefixIndex); return true; } else { localPrefix = string.Empty; } Debug.WriteLine("Given attribute value {0} does not have any prefix value before :", atrValue); return false; } } internal class TestAssemblyLoadContext : AssemblyLoadContext { private AssemblyDependencyResolver _resolver; public TestAssemblyLoadContext(string name, bool isCollectible, string mainAssemblyToLoadPath = null) : base(name, isCollectible) { if (!PlatformDetection.IsBrowser) _resolver = new AssemblyDependencyResolver(mainAssemblyToLoadPath ?? Assembly.GetExecutingAssembly().Location); } protected override Assembly Load(AssemblyName name) { if (PlatformDetection.IsBrowser) { return base.Load(name); } string assemblyPath = _resolver.ResolveAssemblyToPath(name); if (assemblyPath != null) { return LoadFromAssemblyPath(assemblyPath); } return null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using System.Linq; using System.Reflection; using System.Runtime.Loader; using Xunit; internal static class Utils { internal static void Equal<T>(T[] x, T[] y, Func<T, T, bool> f) { if (x == null) { Assert.Null(y); } else if (y == null) { Assert.Null(x); } else { Assert.True(x.Length == y.Length); for (int i = 0; i < x.Length; i++) { Assert.True(f(x[i], y[i])); } } } private static ConcurrentDictionary<string, string> s_prefixToNamespaceDesk = new ConcurrentDictionary<string, string>(); private static ConcurrentDictionary<string, string> s_prefixToNamespaceCoreCLR = new ConcurrentDictionary<string, string>(); internal struct CompareResult { public bool Equal { get; set; } public string ErrorMessage { get; set; } } internal static int Min(int a, int b) { if (a < b) { return a; } return b; } internal static int Max(int a, int b) { if (a > b) { return a; } return b; } private static CompareResult CompareString(string expected, string actual) { if (expected == null && actual == null) { return new CompareResult { Equal = true }; } if (expected == null) { return new CompareResult { ErrorMessage = "expected null, but actual was:\n" + actual }; } if (actual == null) { return new CompareResult { ErrorMessage = "actual was null, but was expecting:\n" + expected }; } int commonLength = Min(actual.Length, expected.Length); for (int currentIndex = 0; currentIndex < commonLength; ++currentIndex) { char expectedChar = expected[currentIndex]; char actualChar = actual[currentIndex]; if (expectedChar != actualChar) { int from = Max(currentIndex - 10, 0); int errPosition = currentIndex - from; int to = Min(currentIndex + 20, commonLength); string message = string.Format("strings differ at index {0}\n{3}\u2193\n[expected]:{1}\n[actual ]:{2}\n{3}\u2191\n[Expected (with length={4})]:\n{5}\n[Actual (with length={6})]:\n{7}", currentIndex, expected.Substring(from, to - from), actual.Substring(from, to - from), new string(' ', errPosition + " expected :".Length), expected.Length, expected, actual.Length, actual); return new CompareResult { ErrorMessage = message }; } } if (actual.Length != commonLength) { return new CompareResult { ErrorMessage = "actual is longer. The unwanted suffix is:\n" + actual.Substring(commonLength) }; } if (expected.Length != commonLength) { return new CompareResult { ErrorMessage = "expected is longer. The missing suffix is:\n" + expected.Substring(commonLength) }; } return new CompareResult { Equal = true }; } internal static CompareResult Compare(string expected, string actual, bool runSmartXmlComparerOnFailure = true) { // for CORECLR we get different xml hence we have updated code for smartyXMLcomparision CompareResult stringcompare = CompareString(expected, actual); if (runSmartXmlComparerOnFailure == true) { if ((stringcompare.Equal != true) && (!string.IsNullOrEmpty(stringcompare.ErrorMessage))) { Debug.WriteLine("Basic baseline XML comparison failed with the error : {0}\n. Running the smart XML comparer", stringcompare.ErrorMessage); if (!SmartXmlCompare(expected, actual)) { return new CompareResult { ErrorMessage = "XML comparison is also failing" }; } else { return new CompareResult { Equal = true }; } } } return stringcompare; } public static bool SmartXmlCompare(string expected, string actual) { XElement deskXElem = XElement.Parse(expected); XElement coreCLRXElem = XElement.Parse(actual); s_prefixToNamespaceDesk.Clear(); s_prefixToNamespaceCoreCLR.Clear(); return CompareXElements(deskXElem, coreCLRXElem); } private static bool CompareXElements(XElement baselineXElement, XElement actualXElement) { // Check whether the XName is the same, this can be done by comparing the two XNames. if (!baselineXElement.Name.Equals(actualXElement.Name)) { // Two nodes could be same even if their localName is not the same. // For example- // Desktop //<GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2zbP0weY4 xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/SerializationTypes"> // <genericData1 z:Id="i2"> // <BaseData></BaseData> // <DerivedData></DerivedData> // </genericData1> // <genericData2 z:Id="i3"> // <BaseData></BaseData> // <DerivedData></DerivedData> // </genericData2> //</GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2zbP0weY4> // vs CoreCLR. //<GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ z:Id="i1" xmlns="http://schemas.datacontract.org/2004/07/SerializationTypes" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"> // <genericData1 z:Id="i2"> // <BaseData /> // <DerivedData /> // </genericData1> // <genericData2 z:Id="i3"> // <BaseData /> // <DerivedData /> // </genericData2> //</GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ> // Note the incorrect padding in the end of GenericBase2OfSimpleBaseDerivedSimpleBaseDerived2RkuXKXCQ // The difference is MD5 hashcode applied to the Type.FullName and is because full typeName in .NET Framework and CoreCLR returns different value. // Hack for the above reason. int deskIdx, coreCLRIdx; if (-1 != (deskIdx = baselineXElement.Name.LocalName.IndexOf("zbP0weY4"))) { // Check if the CoreCLR string contains the other. if (-1 != (coreCLRIdx = actualXElement.Name.LocalName.IndexOf("RkuXKXCQ"))) { // Check whether the substring before this matches if (0 == string.Compare(baselineXElement.Name.LocalName.Substring(0, deskIdx), actualXElement.Name.LocalName.Substring(0, coreCLRIdx))) { // Check if the namespace matched. if (baselineXElement.Name.Namespace.Equals(actualXElement.Name.Namespace)) return true; } } } string message = string.Format("Namespace difference \n[expected]:{0}\n[actual ]:{1}\n Padding expected elements is {2}", baselineXElement.Name.Namespace, actualXElement.Name.Namespace, actualXElement.Name.LocalName ); Debug.WriteLine("Either padding is different or namespace is not matching.\n" + message); return false; } // Comparing attributes XAttribute[] deskAtrs = baselineXElement.Attributes().OrderBy(m => m.Value).ToArray(); XAttribute[] coreCLRAtrs = actualXElement.Attributes().OrderBy(m => m.Value).ToArray(); if (deskAtrs.Length != coreCLRAtrs.Length) { Debug.WriteLine("Number of attributes differ.Expected number of attributes are " + deskAtrs.Length.ToString() + " Actual number of attributes are " + coreCLRAtrs.Length.ToString()); return false; } // At this point the attributes should be all in the same order. for (int i = 0; i < deskAtrs.Length; i++) { if (deskAtrs[i].IsNamespaceDeclaration != coreCLRAtrs[i].IsNamespaceDeclaration) { Debug.WriteLine("Either expected attribute {0} is not namespace declaration or actual attribute {1}", deskAtrs[i].ToString(), coreCLRAtrs[i].ToString()); return false; } if (deskAtrs[i].IsNamespaceDeclaration) { if (0 != string.Compare(deskAtrs[i].Name.NamespaceName, coreCLRAtrs[i].Name.NamespaceName)) { Debug.WriteLine("Namespaces are different.Expected {0} namespace doesn't match with actual {1} namespace ", deskAtrs[i].Name.NamespaceName, coreCLRAtrs[i].Name.NamespaceName); return false; } if (0 != string.Compare(deskAtrs[i].Value, coreCLRAtrs[i].Value)) { Debug.WriteLine("Attribute values are different. Expected {0} attribute values doesn't match with actual {1} attribute value.", deskAtrs[i].Value, coreCLRAtrs[i].Value); return false; } // Update the dictionaries s_prefixToNamespaceDesk[deskAtrs[i].Name.LocalName] = deskAtrs[i].Value; s_prefixToNamespaceCoreCLR[coreCLRAtrs[i].Name.LocalName] = coreCLRAtrs[i].Value; } else { if (!deskAtrs[i].Name.Equals(coreCLRAtrs[i].Name)) { Debug.WriteLine("Attribute names are different. Expected name is {0} but actual name is {1}", deskAtrs[i].Name, coreCLRAtrs[i].Name); return false; } string deskPrefix, coreCLRPrefix; if (IsPrefixedAttributeValue(deskAtrs[i].Value, out deskPrefix)) { if (IsPrefixedAttributeValue(coreCLRAtrs[i].Value, out coreCLRPrefix)) { // Check if they both have the same namespace. XNamespace deskns = baselineXElement.GetNamespaceOfPrefix(deskPrefix); XNamespace coreclrns = actualXElement.GetNamespaceOfPrefix(coreCLRPrefix); if (!deskns.Equals(coreclrns)) { Debug.WriteLine("XML namespace of attribute is different. Expected is {0} but actual is {1}", deskns.NamespaceName, coreclrns.NamespaceName); return false; } // Update the dictionaries s_prefixToNamespaceDesk[deskPrefix] = deskns.NamespaceName; s_prefixToNamespaceCoreCLR[coreCLRPrefix] = coreclrns.NamespaceName; } else { Debug.WriteLine("Either expected {0} or actual {1} attribute value doesn't have prefix :", deskAtrs[i].Value, coreCLRAtrs[i].Value); return false; } } } } if (!CompareValue(baselineXElement.Value, actualXElement.Value)) return false; // Serialized values can only have XElement and XText and hence we do not traverse the complete node structures and only the descendants. XElement[] deskChildElems = baselineXElement.Descendants().OrderBy(m => m.Name.NamespaceName).ToArray(); XElement[] coreCLRChildElems = actualXElement.Descendants().OrderBy(m => m.Name.NamespaceName).ToArray(); if (deskChildElems.Length != coreCLRChildElems.Length) { return false; } for (int i = 0; i < deskChildElems.Length; i++) { if (!CompareXElements(deskChildElems[i], coreCLRChildElems[i])) return false; } // If we have reached here, XML is same. return true; } private static bool CompareValue(string deskElemValue, string coreCLRElemValue) { if (deskElemValue.Equals(coreCLRElemValue)) return true; // For text of the form // <z:QName xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:a="def">a:abc</z:QName> // In the above XML text the XElement.Value is a:abc which in CoreCLR could be something like d1p1:abc // and hence we value check will fail. // To mitigate this we store the namespaces from the parent XElement and use it to check the actual value. string deskPrefix, coreCLRPrefix; if (IsPrefixedAttributeValue(deskElemValue, out deskPrefix)) { if (IsPrefixedAttributeValue(coreCLRElemValue, out coreCLRPrefix)) { // Check whether the prefixes have the right namespaces attached. string deskNs, coreCLRNs; if (s_prefixToNamespaceDesk.TryGetValue(deskPrefix, out deskNs)) { if (s_prefixToNamespaceCoreCLR.TryGetValue(coreCLRPrefix, out coreCLRNs)) { if (deskNs.Equals(coreCLRNs)) { // Also we check that the rest of the strings match. if (0 == string.Compare(deskElemValue.Substring(deskPrefix.Length), coreCLRElemValue.Substring(coreCLRPrefix.Length))) return true; } } } } Debug.WriteLine("Attribute value {0} has empty prefix value before :", coreCLRElemValue); return false; } Debug.WriteLine("Attribute value {0} has empty prefix value before :", deskElemValue); return false; } private static bool IsPrefixedAttributeValue(string atrValue, out string localPrefix) { int prefixIndex = atrValue.IndexOf(":"); if (prefixIndex != -1) { localPrefix = atrValue.Substring(0, prefixIndex); return true; } else { localPrefix = string.Empty; } Debug.WriteLine("Given attribute value {0} does not have any prefix value before :", atrValue); return false; } } internal class TestAssemblyLoadContext : AssemblyLoadContext { private AssemblyDependencyResolver _resolver; public TestAssemblyLoadContext(string name, bool isCollectible, string mainAssemblyToLoadPath = null) : base(name, isCollectible) { if (!PlatformDetection.IsBrowser) _resolver = new AssemblyDependencyResolver(mainAssemblyToLoadPath ?? Assembly.GetExecutingAssembly().Location); } protected override Assembly Load(AssemblyName name) { if (PlatformDetection.IsBrowser) { return base.Load(name); } string assemblyPath = _resolver.ResolveAssemblyToPath(name); if (assemblyPath != null) { return LoadFromAssemblyPath(assemblyPath); } return null; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Common/src/System/Net/ExceptionCheck.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net { internal static class ExceptionCheck { internal static bool IsFatal(Exception exception) => exception is OutOfMemoryException; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net { internal static class ExceptionCheck { internal static bool IsFatal(Exception exception) => exception is OutOfMemoryException; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Directed/shift/uint64.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; namespace ShiftTest { public class CL { public ulong clm_data = 0xFFFFFFFFFFFFFFFF; } public struct VT { public ulong vtm_data; } public class ulong32Test { private static ulong s_data = 0xFFFFFFFFFFFFFFFF; public static ulong f1(ulong arg_data) { arg_data >>= 8; return arg_data; } public static ulong f2(ulong arg_data) { arg_data <<= 8; return arg_data; } public static int Main() { ulong loc_data = 0xFFFFFFFFFFFFFFFF; ulong[] arr_data = new ulong[1]; CL cl = new CL(); VT vt; s_data = 0xFFFFFFFFFFFFFFFF; loc_data = 0xFFFFFFFFFFFFFFFF; arr_data[0] = 0xFFFFFFFFFFFFFFFF; cl.clm_data = 0xFFFFFFFFFFFFFFFF; vt.vtm_data = 0xFFFFFFFFFFFFFFFF; // Test >> Console.WriteLine("The expected result of (0xFFFFFFFFFFFFFFFF>>8) is: {0}", (0xFFFFFFFFFFFFFFFF >> 8)); Console.WriteLine(); Console.WriteLine("The actual result for funciton argument is: {0}", f1(0xFFFFFFFFFFFFFFFF)); loc_data >>= 8; Console.WriteLine("The actual result for local variable is: {0}", loc_data); s_data >>= 8; Console.WriteLine("The actual result for static field is: {0}", s_data); arr_data[0] >>= 8; Console.WriteLine("The actual result for array element is: {0}", arr_data[0]); cl.clm_data >>= 8; Console.WriteLine("The actual result for class member is: {0}", cl.clm_data); vt.vtm_data >>= 8; Console.WriteLine("The actual result for valuestruct member is: {0}", vt.vtm_data); Console.WriteLine(); if (loc_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for local variable"); return -1; } if (f1(0xFFFFFFFFFFFFFFFF) != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for function argument"); return -1; } if (s_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for static field"); return -1; } if (arr_data[0] != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for array element"); return -1; } if (cl.clm_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for class member"); return -1; } if (vt.vtm_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for valuestruct member"); return -1; } // Test << s_data = 0x1; loc_data = 0x1; arr_data[0] = 0x1; cl.clm_data = 0x1; vt.vtm_data = 0x1; Console.WriteLine("The expected result of (0x1<<8) is: {0}", ((ulong)0x1 << 8)); Console.WriteLine(); Console.WriteLine("The actual result for funciton argument is: {0}", f2(0x1)); loc_data <<= 8; Console.WriteLine("The actual result for local variable is: {0}", loc_data); s_data <<= 8; Console.WriteLine("The actual result for static field is: {0}", s_data); arr_data[0] <<= 8; Console.WriteLine("The actual result for array element is: {0}", arr_data[0]); cl.clm_data <<= 8; Console.WriteLine("The actual result for class member is: {0}", cl.clm_data); vt.vtm_data <<= 8; Console.WriteLine("The actual result for valuestruct member is: {0}", vt.vtm_data); Console.WriteLine(); if (loc_data != (0x1 << 8)) { Console.WriteLine("FAILED for local variable"); return -1; } if (f2(0x1) != (0x1 << 8)) { Console.WriteLine("FAILED for function argument"); return -1; } if (s_data != (0x1 << 8)) { Console.WriteLine("FAILED for static field"); return -1; } if (arr_data[0] != (0x1 << 8)) { Console.WriteLine("FAILED for array element"); return -1; } if (cl.clm_data != (0x1 << 8)) { Console.WriteLine("FAILED for class member"); return -1; } if (vt.vtm_data != (0x1 << 8)) { Console.WriteLine("FAILED for valuestruct member"); return -1; } Console.WriteLine("PASSED"); return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; namespace ShiftTest { public class CL { public ulong clm_data = 0xFFFFFFFFFFFFFFFF; } public struct VT { public ulong vtm_data; } public class ulong32Test { private static ulong s_data = 0xFFFFFFFFFFFFFFFF; public static ulong f1(ulong arg_data) { arg_data >>= 8; return arg_data; } public static ulong f2(ulong arg_data) { arg_data <<= 8; return arg_data; } public static int Main() { ulong loc_data = 0xFFFFFFFFFFFFFFFF; ulong[] arr_data = new ulong[1]; CL cl = new CL(); VT vt; s_data = 0xFFFFFFFFFFFFFFFF; loc_data = 0xFFFFFFFFFFFFFFFF; arr_data[0] = 0xFFFFFFFFFFFFFFFF; cl.clm_data = 0xFFFFFFFFFFFFFFFF; vt.vtm_data = 0xFFFFFFFFFFFFFFFF; // Test >> Console.WriteLine("The expected result of (0xFFFFFFFFFFFFFFFF>>8) is: {0}", (0xFFFFFFFFFFFFFFFF >> 8)); Console.WriteLine(); Console.WriteLine("The actual result for funciton argument is: {0}", f1(0xFFFFFFFFFFFFFFFF)); loc_data >>= 8; Console.WriteLine("The actual result for local variable is: {0}", loc_data); s_data >>= 8; Console.WriteLine("The actual result for static field is: {0}", s_data); arr_data[0] >>= 8; Console.WriteLine("The actual result for array element is: {0}", arr_data[0]); cl.clm_data >>= 8; Console.WriteLine("The actual result for class member is: {0}", cl.clm_data); vt.vtm_data >>= 8; Console.WriteLine("The actual result for valuestruct member is: {0}", vt.vtm_data); Console.WriteLine(); if (loc_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for local variable"); return -1; } if (f1(0xFFFFFFFFFFFFFFFF) != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for function argument"); return -1; } if (s_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for static field"); return -1; } if (arr_data[0] != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for array element"); return -1; } if (cl.clm_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for class member"); return -1; } if (vt.vtm_data != (0xFFFFFFFFFFFFFFFF >> 8)) { Console.WriteLine("FAILED for valuestruct member"); return -1; } // Test << s_data = 0x1; loc_data = 0x1; arr_data[0] = 0x1; cl.clm_data = 0x1; vt.vtm_data = 0x1; Console.WriteLine("The expected result of (0x1<<8) is: {0}", ((ulong)0x1 << 8)); Console.WriteLine(); Console.WriteLine("The actual result for funciton argument is: {0}", f2(0x1)); loc_data <<= 8; Console.WriteLine("The actual result for local variable is: {0}", loc_data); s_data <<= 8; Console.WriteLine("The actual result for static field is: {0}", s_data); arr_data[0] <<= 8; Console.WriteLine("The actual result for array element is: {0}", arr_data[0]); cl.clm_data <<= 8; Console.WriteLine("The actual result for class member is: {0}", cl.clm_data); vt.vtm_data <<= 8; Console.WriteLine("The actual result for valuestruct member is: {0}", vt.vtm_data); Console.WriteLine(); if (loc_data != (0x1 << 8)) { Console.WriteLine("FAILED for local variable"); return -1; } if (f2(0x1) != (0x1 << 8)) { Console.WriteLine("FAILED for function argument"); return -1; } if (s_data != (0x1 << 8)) { Console.WriteLine("FAILED for static field"); return -1; } if (arr_data[0] != (0x1 << 8)) { Console.WriteLine("FAILED for array element"); return -1; } if (cl.clm_data != (0x1 << 8)) { Console.WriteLine("FAILED for class member"); return -1; } if (vt.vtm_data != (0x1 << 8)) { Console.WriteLine("FAILED for valuestruct member"); return -1; } Console.WriteLine("PASSED"); return 100; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/X86/Bmi1.X64/ExtractLowestSetBit.UInt64.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 ExtractLowestSetBitUInt64() { var test = new ScalarUnaryOpTest__ExtractLowestSetBitUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned 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(); } 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 ScalarUnaryOpTest__ExtractLowestSetBitUInt64 { private struct TestStruct { public UInt64 _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = TestLibrary.Generator.GetUInt64(); return testStruct; } public void RunStructFldScenario(ScalarUnaryOpTest__ExtractLowestSetBitUInt64 testClass) { var result = Bmi1.X64.ExtractLowestSetBit(_fld); testClass.ValidateResult(_fld, result); } } private static UInt64 _data; private static UInt64 _clsVar; private UInt64 _fld; static ScalarUnaryOpTest__ExtractLowestSetBitUInt64() { _clsVar = TestLibrary.Generator.GetUInt64(); } public ScalarUnaryOpTest__ExtractLowestSetBitUInt64() { Succeeded = true; _fld = TestLibrary.Generator.GetUInt64(); _data = TestLibrary.Generator.GetUInt64(); } public bool IsSupported => Bmi1.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Bmi1.X64.ExtractLowestSetBit( Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) ); ValidateResult(_data, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.ExtractLowestSetBit), new Type[] { typeof(UInt64) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) }); ValidateResult(_data, (UInt64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Bmi1.X64.ExtractLowestSetBit( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)); var result = Bmi1.X64.ExtractLowestSetBit(data); ValidateResult(data, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarUnaryOpTest__ExtractLowestSetBitUInt64(); var result = Bmi1.X64.ExtractLowestSetBit(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Bmi1.X64.ExtractLowestSetBit(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Bmi1.X64.ExtractLowestSetBit(test._fld); ValidateResult(test._fld, result); } 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(UInt64 data, UInt64 result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; isUnexpectedResult = ((unchecked((ulong)(-(long)data)) & data) != result); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.ExtractLowestSetBit)}<UInt64>(UInt64): ExtractLowestSetBit failed:"); TestLibrary.TestFramework.LogInformation($" data: {data}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractLowestSetBitUInt64() { var test = new ScalarUnaryOpTest__ExtractLowestSetBitUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned 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(); } 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 ScalarUnaryOpTest__ExtractLowestSetBitUInt64 { private struct TestStruct { public UInt64 _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = TestLibrary.Generator.GetUInt64(); return testStruct; } public void RunStructFldScenario(ScalarUnaryOpTest__ExtractLowestSetBitUInt64 testClass) { var result = Bmi1.X64.ExtractLowestSetBit(_fld); testClass.ValidateResult(_fld, result); } } private static UInt64 _data; private static UInt64 _clsVar; private UInt64 _fld; static ScalarUnaryOpTest__ExtractLowestSetBitUInt64() { _clsVar = TestLibrary.Generator.GetUInt64(); } public ScalarUnaryOpTest__ExtractLowestSetBitUInt64() { Succeeded = true; _fld = TestLibrary.Generator.GetUInt64(); _data = TestLibrary.Generator.GetUInt64(); } public bool IsSupported => Bmi1.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Bmi1.X64.ExtractLowestSetBit( Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) ); ValidateResult(_data, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.ExtractLowestSetBit), new Type[] { typeof(UInt64) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) }); ValidateResult(_data, (UInt64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Bmi1.X64.ExtractLowestSetBit( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)); var result = Bmi1.X64.ExtractLowestSetBit(data); ValidateResult(data, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarUnaryOpTest__ExtractLowestSetBitUInt64(); var result = Bmi1.X64.ExtractLowestSetBit(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Bmi1.X64.ExtractLowestSetBit(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Bmi1.X64.ExtractLowestSetBit(test._fld); ValidateResult(test._fld, result); } 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(UInt64 data, UInt64 result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; isUnexpectedResult = ((unchecked((ulong)(-(long)data)) & data) != result); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.ExtractLowestSetBit)}<UInt64>(UInt64): ExtractLowestSetBit failed:"); TestLibrary.TestFramework.LogInformation($" data: {data}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/generics/box-unbox-generics027.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ<T>(T o) { return Helper.Compare((NotEmptyStructGen<int>)(object)o, Helper.Create(default(NotEmptyStructGen<int>))); } private static bool BoxUnboxToQ<T>(T o) { return Helper.Compare((NotEmptyStructGen<int>?)(object)o, Helper.Create(default(NotEmptyStructGen<int>))); } private static int Main() { NotEmptyStructGen<int>? s = Helper.Create(default(NotEmptyStructGen<int>)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ<T>(T o) { return Helper.Compare((NotEmptyStructGen<int>)(object)o, Helper.Create(default(NotEmptyStructGen<int>))); } private static bool BoxUnboxToQ<T>(T o) { return Helper.Compare((NotEmptyStructGen<int>?)(object)o, Helper.Create(default(NotEmptyStructGen<int>))); } private static int Main() { NotEmptyStructGen<int>? s = Helper.Create(default(NotEmptyStructGen<int>)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/X86/Sse3/MoveAndDuplicate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Sse3.IsSupported) { using (TestTable<double> doubleTable = new TestTable<double>(new double[2] { 1, -5 }, new double[2])) { var vf1 = Unsafe.Read<Vector128<double>>(doubleTable.inArrayPtr); var vf2 = Sse3.MoveAndDuplicate(vf1); Unsafe.Write(doubleTable.outArrayPtr, vf2); if (BitConverter.DoubleToInt64Bits(doubleTable.inArray[0]) != BitConverter.DoubleToInt64Bits(doubleTable.outArray[0]) || BitConverter.DoubleToInt64Bits(doubleTable.inArray[0]) != BitConverter.DoubleToInt64Bits(doubleTable.outArray[1])) { Console.WriteLine("Sse3 MoveAndDuplicate failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray; public T[] outArray; public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle; GCHandle outHandle; public TestTable(T[] a, T[] b) { this.inArray = a; this.outArray = b; inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T, T, bool> check) { for (int i = 0; i < inArray.Length; i++) { if (!check(inArray[i], outArray[i])) { return false; } } return true; } public void Dispose() { inHandle.Free(); outHandle.Free(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Sse3.IsSupported) { using (TestTable<double> doubleTable = new TestTable<double>(new double[2] { 1, -5 }, new double[2])) { var vf1 = Unsafe.Read<Vector128<double>>(doubleTable.inArrayPtr); var vf2 = Sse3.MoveAndDuplicate(vf1); Unsafe.Write(doubleTable.outArrayPtr, vf2); if (BitConverter.DoubleToInt64Bits(doubleTable.inArray[0]) != BitConverter.DoubleToInt64Bits(doubleTable.outArray[0]) || BitConverter.DoubleToInt64Bits(doubleTable.inArray[0]) != BitConverter.DoubleToInt64Bits(doubleTable.outArray[1])) { Console.WriteLine("Sse3 MoveAndDuplicate failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray; public T[] outArray; public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle; GCHandle outHandle; public TestTable(T[] a, T[] b) { this.inArray = a; this.outArray = b; inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T, T, bool> check) { for (int i = 0; i < inArray.Length; i++) { if (!check(inArray[i], outArray[i])) { return false; } } return true; } public void Dispose() { inHandle.Free(); outHandle.Free(); } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/StringLengthAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.ComponentModel.DataAnnotations.Tests { public class StringLengthAttributeTests : ValidationAttributeTestBase { protected override IEnumerable<TestCase> ValidValues() { yield return new TestCase(new StringLengthAttribute(12), null); yield return new TestCase(new StringLengthAttribute(12), string.Empty); yield return new TestCase(new StringLengthAttribute(12), "Valid string"); yield return new TestCase(new StringLengthAttribute(12) { MinimumLength = 5 }, "Valid"); yield return new TestCase(new StringLengthAttribute(12) { MinimumLength = 5 }, "Valid string"); } protected override IEnumerable<TestCase> InvalidValues() { yield return new TestCase(new StringLengthAttribute(12), "Invalid string"); yield return new TestCase(new StringLengthAttribute(12) {MinimumLength = 8 }, "Invalid"); } [Theory] [InlineData(42)] [InlineData(-1)] public static void Ctor_Int(int maximumLength) { var attribute = new StringLengthAttribute(maximumLength); Assert.Equal(maximumLength, attribute.MaximumLength); Assert.Equal(0, attribute.MinimumLength); } [Theory] [InlineData(29)] public static void MinimumLength_GetSet_RetunsExpected(int newValue) { var attribute = new StringLengthAttribute(42); attribute.MinimumLength = newValue; Assert.Equal(newValue, attribute.MinimumLength); } [Fact] public static void Validate_NegativeMaximumLength_ThrowsInvalidOperationException() { var attribute = new StringLengthAttribute(-1); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); } [Fact] public static void Validate_MinimumLengthGreaterThanMaximumLength_ThrowsInvalidOperationException() { var attribute = new StringLengthAttribute(42) { MinimumLength = 43 }; Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); } [Fact] public static void Validate_ValueNotString_ThrowsInvalidCastException() { var attribute = new StringLengthAttribute(42); Assert.Throws<InvalidCastException>(() => attribute.Validate(new object(), new ValidationContext(new object()))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.ComponentModel.DataAnnotations.Tests { public class StringLengthAttributeTests : ValidationAttributeTestBase { protected override IEnumerable<TestCase> ValidValues() { yield return new TestCase(new StringLengthAttribute(12), null); yield return new TestCase(new StringLengthAttribute(12), string.Empty); yield return new TestCase(new StringLengthAttribute(12), "Valid string"); yield return new TestCase(new StringLengthAttribute(12) { MinimumLength = 5 }, "Valid"); yield return new TestCase(new StringLengthAttribute(12) { MinimumLength = 5 }, "Valid string"); } protected override IEnumerable<TestCase> InvalidValues() { yield return new TestCase(new StringLengthAttribute(12), "Invalid string"); yield return new TestCase(new StringLengthAttribute(12) {MinimumLength = 8 }, "Invalid"); } [Theory] [InlineData(42)] [InlineData(-1)] public static void Ctor_Int(int maximumLength) { var attribute = new StringLengthAttribute(maximumLength); Assert.Equal(maximumLength, attribute.MaximumLength); Assert.Equal(0, attribute.MinimumLength); } [Theory] [InlineData(29)] public static void MinimumLength_GetSet_RetunsExpected(int newValue) { var attribute = new StringLengthAttribute(42); attribute.MinimumLength = newValue; Assert.Equal(newValue, attribute.MinimumLength); } [Fact] public static void Validate_NegativeMaximumLength_ThrowsInvalidOperationException() { var attribute = new StringLengthAttribute(-1); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); } [Fact] public static void Validate_MinimumLengthGreaterThanMaximumLength_ThrowsInvalidOperationException() { var attribute = new StringLengthAttribute(42) { MinimumLength = 43 }; Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); } [Fact] public static void Validate_ValueNotString_ThrowsInvalidCastException() { var attribute = new StringLengthAttribute(42); Assert.Throws<InvalidCastException>(() => attribute.Validate(new object(), new ValidationContext(new object()))); } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Private.CoreLib/src/System/Reflection/InvalidFilterCriteriaException.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Serialization; namespace System.Reflection { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidFilterCriteriaException : ApplicationException { public InvalidFilterCriteriaException() : this(SR.Arg_InvalidFilterCriteriaException) { } public InvalidFilterCriteriaException(string? message) : this(message, null) { } public InvalidFilterCriteriaException(string? message, Exception? inner) : base(message, inner) { HResult = HResults.COR_E_INVALIDFILTERCRITERIA; } protected InvalidFilterCriteriaException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Serialization; namespace System.Reflection { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidFilterCriteriaException : ApplicationException { public InvalidFilterCriteriaException() : this(SR.Arg_InvalidFilterCriteriaException) { } public InvalidFilterCriteriaException(string? message) : this(message, null) { } public InvalidFilterCriteriaException(string? message, Exception? inner) : base(message, inner) { HResult = HResults.COR_E_INVALIDFILTERCRITERIA; } protected InvalidFilterCriteriaException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.CurrentUserOnly.Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.DirectoryServices.AccountManagement; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { // Class to be used as xUnit fixture to avoid creating the user, an relatively slow operation (couple of seconds), multiple times. public class TestAccountImpersonator : IDisposable { private const string TestAccountName = "CorFxTst0uZa"; // Random suffix to avoid matching any other account by accident, but const to avoid leaking it. private SafeAccessTokenHandle _testAccountTokenHandle; public TestAccountImpersonator() { string testAccountPassword; byte[] randomBytes = RandomNumberGenerator.GetBytes(33); // Add special chars to ensure it satisfies password requirements. testAccountPassword = Convert.ToBase64String(randomBytes) + "_-As@!%*(1)4#2"; DateTime accountExpirationDate = DateTime.UtcNow + TimeSpan.FromMinutes(2); using (var principalCtx = new PrincipalContext(ContextType.Machine)) { bool needToCreate = false; using (var foundUserPrincipal = UserPrincipal.FindByIdentity(principalCtx, TestAccountName)) { if (foundUserPrincipal == null) { needToCreate = true; } else { // Somehow the account leaked from previous runs, however, password is lost, reset it. foundUserPrincipal.SetPassword(testAccountPassword); foundUserPrincipal.AccountExpirationDate = accountExpirationDate; foundUserPrincipal.Save(); } } if (needToCreate) { using (var userPrincipal = new UserPrincipal(principalCtx)) { userPrincipal.SetPassword(testAccountPassword); userPrincipal.AccountExpirationDate = accountExpirationDate; userPrincipal.Name = TestAccountName; userPrincipal.DisplayName = TestAccountName; userPrincipal.Description = TestAccountName; userPrincipal.Save(); } } } const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; if (!LogonUser(TestAccountName, ".", testAccountPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out _testAccountTokenHandle)) { _testAccountTokenHandle = null; throw new Exception($"Failed to get SafeAccessTokenHandle for test account {TestAccountName}", new Win32Exception()); } } public void Dispose() { if (_testAccountTokenHandle == null) return; _testAccountTokenHandle.Dispose(); _testAccountTokenHandle = null; using (var principalCtx = new PrincipalContext(ContextType.Machine)) using (var userPrincipal = UserPrincipal.FindByIdentity(principalCtx, TestAccountName)) { if (userPrincipal == null) throw new Exception($"Failed to get user principal to delete test account {TestAccountName}"); try { userPrincipal.Delete(); } catch (InvalidOperationException) { // TODO: Investigate, it always throw this exception with "Can't delete object already deleted", but it actually deletes it. } } } // This method asserts if it impersonates the current identity, i.e.: it ensures that an actual impersonation happens public void RunImpersonated(Action action) { using (WindowsIdentity serverIdentity = WindowsIdentity.GetCurrent()) { WindowsIdentity.RunImpersonated(_testAccountTokenHandle, () => { using (WindowsIdentity clientIdentity = WindowsIdentity.GetCurrent()) Assert.NotEqual(serverIdentity.Name, clientIdentity.Name); action(); }); } } [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out SafeAccessTokenHandle safeAccessTokenHandle); } /// <summary> /// Negative tests for PipeOptions.CurrentUserOnly in Windows. /// </summary> public class NamedPipeTest_CurrentUserOnly_Windows : IClassFixture<TestAccountImpersonator> { public static bool IsAdminOnSupportedWindowsVersions => PlatformDetection.IsWindowsAndElevated && !PlatformDetection.IsWindows7 && !PlatformDetection.IsWindowsNanoServer && !PlatformDetection.IsWindowsServerCore; private TestAccountImpersonator _testAccountImpersonator; public NamedPipeTest_CurrentUserOnly_Windows(TestAccountImpersonator testAccountImpersonator) { _testAccountImpersonator = testAccountImpersonator; } [OuterLoop] [ConditionalTheory(nameof(IsAdminOnSupportedWindowsVersions))] [InlineData(PipeOptions.None, PipeOptions.None)] [InlineData(PipeOptions.None, PipeOptions.CurrentUserOnly)] [InlineData(PipeOptions.CurrentUserOnly, PipeOptions.None)] [InlineData(PipeOptions.CurrentUserOnly, PipeOptions.CurrentUserOnly)] public void Connection_UnderDifferentUsers_BehavesAsExpected( PipeOptions serverPipeOptions, PipeOptions clientPipeOptions) { string name = PipeStreamConformanceTests.GetUniquePipeName(); using (var cts = new CancellationTokenSource()) using (var server = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverPipeOptions | PipeOptions.Asynchronous)) { Task serverTask = server.WaitForConnectionAsync(cts.Token); _testAccountImpersonator.RunImpersonated(() => { using (var client = new NamedPipeClientStream(".", name, PipeDirection.InOut, clientPipeOptions)) { Assert.Throws<UnauthorizedAccessException>(() => client.Connect()); } }); // Server is expected to not have received any request. cts.Cancel(); AggregateException e = Assert.Throws<AggregateException>(() => serverTask.Wait(10_000)); Assert.IsType<TaskCanceledException>(e.InnerException); } } [OuterLoop] [ConditionalFact(nameof(IsAdminOnSupportedWindowsVersions))] public void Allow_Connection_UnderDifferentUsers_ForClientReading() { string name = PipeStreamConformanceTests.GetUniquePipeName(); using (var server = new NamedPipeServerStream( name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { Task serverTask = server.WaitForConnectionAsync(CancellationToken.None); _testAccountImpersonator.RunImpersonated(() => { using (var client = new NamedPipeClientStream(".", name, PipeDirection.In)) { client.Connect(10_000); } }); Assert.True(serverTask.Wait(10_000)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.DirectoryServices.AccountManagement; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { // Class to be used as xUnit fixture to avoid creating the user, an relatively slow operation (couple of seconds), multiple times. public class TestAccountImpersonator : IDisposable { private const string TestAccountName = "CorFxTst0uZa"; // Random suffix to avoid matching any other account by accident, but const to avoid leaking it. private SafeAccessTokenHandle _testAccountTokenHandle; public TestAccountImpersonator() { string testAccountPassword; byte[] randomBytes = RandomNumberGenerator.GetBytes(33); // Add special chars to ensure it satisfies password requirements. testAccountPassword = Convert.ToBase64String(randomBytes) + "_-As@!%*(1)4#2"; DateTime accountExpirationDate = DateTime.UtcNow + TimeSpan.FromMinutes(2); using (var principalCtx = new PrincipalContext(ContextType.Machine)) { bool needToCreate = false; using (var foundUserPrincipal = UserPrincipal.FindByIdentity(principalCtx, TestAccountName)) { if (foundUserPrincipal == null) { needToCreate = true; } else { // Somehow the account leaked from previous runs, however, password is lost, reset it. foundUserPrincipal.SetPassword(testAccountPassword); foundUserPrincipal.AccountExpirationDate = accountExpirationDate; foundUserPrincipal.Save(); } } if (needToCreate) { using (var userPrincipal = new UserPrincipal(principalCtx)) { userPrincipal.SetPassword(testAccountPassword); userPrincipal.AccountExpirationDate = accountExpirationDate; userPrincipal.Name = TestAccountName; userPrincipal.DisplayName = TestAccountName; userPrincipal.Description = TestAccountName; userPrincipal.Save(); } } } const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; if (!LogonUser(TestAccountName, ".", testAccountPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out _testAccountTokenHandle)) { _testAccountTokenHandle = null; throw new Exception($"Failed to get SafeAccessTokenHandle for test account {TestAccountName}", new Win32Exception()); } } public void Dispose() { if (_testAccountTokenHandle == null) return; _testAccountTokenHandle.Dispose(); _testAccountTokenHandle = null; using (var principalCtx = new PrincipalContext(ContextType.Machine)) using (var userPrincipal = UserPrincipal.FindByIdentity(principalCtx, TestAccountName)) { if (userPrincipal == null) throw new Exception($"Failed to get user principal to delete test account {TestAccountName}"); try { userPrincipal.Delete(); } catch (InvalidOperationException) { // TODO: Investigate, it always throw this exception with "Can't delete object already deleted", but it actually deletes it. } } } // This method asserts if it impersonates the current identity, i.e.: it ensures that an actual impersonation happens public void RunImpersonated(Action action) { using (WindowsIdentity serverIdentity = WindowsIdentity.GetCurrent()) { WindowsIdentity.RunImpersonated(_testAccountTokenHandle, () => { using (WindowsIdentity clientIdentity = WindowsIdentity.GetCurrent()) Assert.NotEqual(serverIdentity.Name, clientIdentity.Name); action(); }); } } [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out SafeAccessTokenHandle safeAccessTokenHandle); } /// <summary> /// Negative tests for PipeOptions.CurrentUserOnly in Windows. /// </summary> public class NamedPipeTest_CurrentUserOnly_Windows : IClassFixture<TestAccountImpersonator> { public static bool IsAdminOnSupportedWindowsVersions => PlatformDetection.IsWindowsAndElevated && !PlatformDetection.IsWindows7 && !PlatformDetection.IsWindowsNanoServer && !PlatformDetection.IsWindowsServerCore; private TestAccountImpersonator _testAccountImpersonator; public NamedPipeTest_CurrentUserOnly_Windows(TestAccountImpersonator testAccountImpersonator) { _testAccountImpersonator = testAccountImpersonator; } [OuterLoop] [ConditionalTheory(nameof(IsAdminOnSupportedWindowsVersions))] [InlineData(PipeOptions.None, PipeOptions.None)] [InlineData(PipeOptions.None, PipeOptions.CurrentUserOnly)] [InlineData(PipeOptions.CurrentUserOnly, PipeOptions.None)] [InlineData(PipeOptions.CurrentUserOnly, PipeOptions.CurrentUserOnly)] public void Connection_UnderDifferentUsers_BehavesAsExpected( PipeOptions serverPipeOptions, PipeOptions clientPipeOptions) { string name = PipeStreamConformanceTests.GetUniquePipeName(); using (var cts = new CancellationTokenSource()) using (var server = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverPipeOptions | PipeOptions.Asynchronous)) { Task serverTask = server.WaitForConnectionAsync(cts.Token); _testAccountImpersonator.RunImpersonated(() => { using (var client = new NamedPipeClientStream(".", name, PipeDirection.InOut, clientPipeOptions)) { Assert.Throws<UnauthorizedAccessException>(() => client.Connect()); } }); // Server is expected to not have received any request. cts.Cancel(); AggregateException e = Assert.Throws<AggregateException>(() => serverTask.Wait(10_000)); Assert.IsType<TaskCanceledException>(e.InnerException); } } [OuterLoop] [ConditionalFact(nameof(IsAdminOnSupportedWindowsVersions))] public void Allow_Connection_UnderDifferentUsers_ForClientReading() { string name = PipeStreamConformanceTests.GetUniquePipeName(); using (var server = new NamedPipeServerStream( name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { Task serverTask = server.WaitForConnectionAsync(CancellationToken.None); _testAccountImpersonator.RunImpersonated(() => { using (var client = new NamedPipeClientStream(".", name, PipeDirection.In)) { client.Connect(10_000); } }); Assert.True(serverTask.Wait(10_000)); } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/CodeGenBringUpTests/addref.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; class child { static int Main() { const int Pass = 100; const int Fail = -1; int x = 1; int result = addref(1, ref x); if (result == 2) return Pass; else return Fail; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int addref(int x, ref int a) { x += a; return x; } }
// 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; class child { static int Main() { const int Pass = 100; const int Fail = -1; int x = 1; int result = addref(1, ref x); if (result == 2) return Pass; else return Fail; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int addref(int x, ref int a) { x += a; return x; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/GetStartComSlotTests.Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class GetStartComSlotTests { public static IEnumerable<object[]> GetStartComSlot_TestData() { yield return new object[] { typeof(ComImportObject), -1 }; yield return new object[] { typeof(SubComImportObject), -1 }; yield return new object[] { typeof(InterfaceComImportObject), -1 }; yield return new object[] { typeof(InterfaceAndComImportObject), 7 }; yield return new object[] { typeof(IComImportObject), 7 }; yield return new object[] { typeof(DualInterface), 7}; yield return new object[] { typeof(IUnknownInterface), 3}; yield return new object[] { typeof(IDispatchInterface), 7}; yield return new object[] { typeof(DualComObject), 7}; yield return new object[] { typeof(IUnknownComObject), 3}; yield return new object[] { typeof(IDispatchComObject), 7}; yield return new object[] { typeof(NonDualComObject), 7}; yield return new object[] { typeof(AutoDispatchComObject), 7}; yield return new object[] { typeof(AutoDualComObject), 7}; yield return new object[] { typeof(NonDualComObjectEmpty), -1}; yield return new object[] { typeof(AutoDispatchComObjectEmpty), -1}; yield return new object[] { typeof(AutoDualComObjectEmpty), -1}; yield return new object[] { typeof(ManagedInterfaceSupportIUnknown), 3 }; yield return new object[] { typeof(ManagedInterfaceSupportIUnknownWithMethods), 3 }; yield return new object[] { typeof(ManagedInterfaceSupportDualInterfaceWithMethods), 7 }; yield return new object[] { typeof(ManagedInterfaceSupportIDispatch), 7 }; yield return new object[] { typeof(ManagedInterfaceSupportIDispatchWithMethods), 7 }; yield return new object[] { typeof(ManagedAutoDispatchClass), -1 }; yield return new object[] { typeof(ManagedAutoDualClass), 7 }; } [MemberData(nameof(GetStartComSlot_TestData))] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void GetStartComSlot_Windows_ReturnsExpected(Type type, int expected) { Assert.Equal(expected, Marshal.GetStartComSlot(type)); } [ConditionalFact(typeof(PlatformDetection), nameof (PlatformDetection.IsNotWindowsNanoServer))] public void GetStartComSlot_ManagedIInspectableObject_Fail() { Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetStartComSlot(typeof(IInspectableInterface))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class GetStartComSlotTests { public static IEnumerable<object[]> GetStartComSlot_TestData() { yield return new object[] { typeof(ComImportObject), -1 }; yield return new object[] { typeof(SubComImportObject), -1 }; yield return new object[] { typeof(InterfaceComImportObject), -1 }; yield return new object[] { typeof(InterfaceAndComImportObject), 7 }; yield return new object[] { typeof(IComImportObject), 7 }; yield return new object[] { typeof(DualInterface), 7}; yield return new object[] { typeof(IUnknownInterface), 3}; yield return new object[] { typeof(IDispatchInterface), 7}; yield return new object[] { typeof(DualComObject), 7}; yield return new object[] { typeof(IUnknownComObject), 3}; yield return new object[] { typeof(IDispatchComObject), 7}; yield return new object[] { typeof(NonDualComObject), 7}; yield return new object[] { typeof(AutoDispatchComObject), 7}; yield return new object[] { typeof(AutoDualComObject), 7}; yield return new object[] { typeof(NonDualComObjectEmpty), -1}; yield return new object[] { typeof(AutoDispatchComObjectEmpty), -1}; yield return new object[] { typeof(AutoDualComObjectEmpty), -1}; yield return new object[] { typeof(ManagedInterfaceSupportIUnknown), 3 }; yield return new object[] { typeof(ManagedInterfaceSupportIUnknownWithMethods), 3 }; yield return new object[] { typeof(ManagedInterfaceSupportDualInterfaceWithMethods), 7 }; yield return new object[] { typeof(ManagedInterfaceSupportIDispatch), 7 }; yield return new object[] { typeof(ManagedInterfaceSupportIDispatchWithMethods), 7 }; yield return new object[] { typeof(ManagedAutoDispatchClass), -1 }; yield return new object[] { typeof(ManagedAutoDualClass), 7 }; } [MemberData(nameof(GetStartComSlot_TestData))] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void GetStartComSlot_Windows_ReturnsExpected(Type type, int expected) { Assert.Equal(expected, Marshal.GetStartComSlot(type)); } [ConditionalFact(typeof(PlatformDetection), nameof (PlatformDetection.IsNotWindowsNanoServer))] public void GetStartComSlot_ManagedIInspectableObject_Fail() { Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetStartComSlot(typeof(IInspectableInterface))); } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Data.Common/tests/System/Data/InRowChangingEventExceptionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (c) 2004 Mainsoft Co. // // 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. // using Xunit; namespace System.Data.Tests { public class InRowChangingEventExceptionTest { private bool _eventTriggered = false; [Fact] public void Generate() { DataTable dt = DataProvider.CreateParentDataTable(); dt.RowChanging += new DataRowChangeEventHandler(Row_Changing); dt.Rows[0][1] = "NewValue"; //this event must be raised in order to test the exception // RowChanging - Event raised Assert.True(_eventTriggered); } private void Row_Changing(object sender, DataRowChangeEventArgs e) { // InRowChangingEventException - EndEdit Assert.Throws<InRowChangingEventException>(() => { e.Row.EndEdit(); //can't invoke EndEdit while in ChangingEvent }); _eventTriggered = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (c) 2004 Mainsoft Co. // // 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. // using Xunit; namespace System.Data.Tests { public class InRowChangingEventExceptionTest { private bool _eventTriggered = false; [Fact] public void Generate() { DataTable dt = DataProvider.CreateParentDataTable(); dt.RowChanging += new DataRowChangeEventHandler(Row_Changing); dt.Rows[0][1] = "NewValue"; //this event must be raised in order to test the exception // RowChanging - Event raised Assert.True(_eventTriggered); } private void Row_Changing(object sender, DataRowChangeEventArgs e) { // InRowChangingEventException - EndEdit Assert.Throws<InRowChangingEventException>(() => { e.Row.EndEdit(); //can't invoke EndEdit while in ChangingEvent }); _eventTriggered = true; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Linq.Expressions/tests/Dynamic/GetMemberBinderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Microsoft.CSharp.RuntimeBinder; using Xunit; namespace System.Dynamic.Tests { public class GetMemberBinderTests { private class MinimumOverrideGetMemberBinder : GetMemberBinder { public MinimumOverrideGetMemberBinder(string name, bool ignoreCase) : base(name, ignoreCase) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { throw new NotSupportedException(); } } private class TestBaseClass { public string Name => nameof(TestBaseClass); } private class TestDerivedClass : TestBaseClass { public new string Name => nameof(TestDerivedClass); } private static readonly string[] Names = { "arg", "ARG", "Arg", "Argument name that isn\u2019t a valid C\u266F name \uD83D\uDC7F\uD83E\uDD22", "horrid name with" + (char)0xD800 + "a half surrogate", "new", "break" }; public static IEnumerable<object[]> NamesAndBools() => Names.Select((n, i) => new object[] {n, i % 2 == 0}); [Fact] public void InvokeInstanceProperty() { dynamic d = "1234"; Assert.Equal(4, d.Length); } [Fact] public void InvokeGenericClassInstanceProperty() { dynamic d = new List<int> {1, 2, 3, 4}; Assert.Equal(4, d.Count); } [Fact] public void InvokeCaseInsensitiveFails() { dynamic d = "1234"; Assert.Throws<RuntimeBinderException>(() => d.LENGTH); } [Fact] public void MemberHiding() { dynamic d = new TestDerivedClass(); Assert.Equal(nameof(TestDerivedClass), d.Name); } [Fact] public void NullName() { AssertExtensions.Throws<ArgumentNullException>("name", () => new MinimumOverrideGetMemberBinder(null, false)); AssertExtensions.Throws<ArgumentNullException>("name", () => new MinimumOverrideGetMemberBinder(null, true)); } [Theory, MemberData(nameof(NamesAndBools))] public void CTorArgumentsStored(string name, bool ignoreCase) { GetMemberBinder binder = new MinimumOverrideGetMemberBinder(name, ignoreCase); Assert.Equal(ignoreCase, binder.IgnoreCase); Assert.Equal(binder.Name, name); } [Theory, MemberData(nameof(NamesAndBools))] public void ReturnTypeObject(string name, bool ignoreCase) => Assert.Equal(typeof(object), new MinimumOverrideGetMemberBinder(name, ignoreCase).ReturnType); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Microsoft.CSharp.RuntimeBinder; using Xunit; namespace System.Dynamic.Tests { public class GetMemberBinderTests { private class MinimumOverrideGetMemberBinder : GetMemberBinder { public MinimumOverrideGetMemberBinder(string name, bool ignoreCase) : base(name, ignoreCase) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { throw new NotSupportedException(); } } private class TestBaseClass { public string Name => nameof(TestBaseClass); } private class TestDerivedClass : TestBaseClass { public new string Name => nameof(TestDerivedClass); } private static readonly string[] Names = { "arg", "ARG", "Arg", "Argument name that isn\u2019t a valid C\u266F name \uD83D\uDC7F\uD83E\uDD22", "horrid name with" + (char)0xD800 + "a half surrogate", "new", "break" }; public static IEnumerable<object[]> NamesAndBools() => Names.Select((n, i) => new object[] {n, i % 2 == 0}); [Fact] public void InvokeInstanceProperty() { dynamic d = "1234"; Assert.Equal(4, d.Length); } [Fact] public void InvokeGenericClassInstanceProperty() { dynamic d = new List<int> {1, 2, 3, 4}; Assert.Equal(4, d.Count); } [Fact] public void InvokeCaseInsensitiveFails() { dynamic d = "1234"; Assert.Throws<RuntimeBinderException>(() => d.LENGTH); } [Fact] public void MemberHiding() { dynamic d = new TestDerivedClass(); Assert.Equal(nameof(TestDerivedClass), d.Name); } [Fact] public void NullName() { AssertExtensions.Throws<ArgumentNullException>("name", () => new MinimumOverrideGetMemberBinder(null, false)); AssertExtensions.Throws<ArgumentNullException>("name", () => new MinimumOverrideGetMemberBinder(null, true)); } [Theory, MemberData(nameof(NamesAndBools))] public void CTorArgumentsStored(string name, bool ignoreCase) { GetMemberBinder binder = new MinimumOverrideGetMemberBinder(name, ignoreCase); Assert.Equal(ignoreCase, binder.IgnoreCase); Assert.Equal(binder.Name, name); } [Theory, MemberData(nameof(NamesAndBools))] public void ReturnTypeObject(string name, bool ignoreCase) => Assert.Equal(typeof(object), new MinimumOverrideGetMemberBinder(name, ignoreCase).ReturnType); } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EditableAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.ComponentModel.DataAnnotations { /// <summary> /// Indicates whether the consumer of a field or property, such as a client application, /// should allow editing of the value. /// </summary> /// <remarks> /// This attribute neither enforces nor guarantees editability; the underlying data /// store might allow changing the data regardless of this attribute. The presence /// of this attribute signals intent to the consumer of the attribute whether or not /// the end user should be allowed to change the value via the client application. /// </remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class EditableAttribute : Attribute { /// <summary> /// Indicate whether or not a field/property is editable. /// </summary> /// <param name="allowEdit"> /// Indicates whether the field/property is editable. The value provided /// will apply to both <see cref="AllowEdit" /> and /// <see cref="AllowInitialValue" /> unless the <see cref="AllowInitialValue" /> /// property is explicitly specified. /// </param> public EditableAttribute(bool allowEdit) { AllowEdit = allowEdit; AllowInitialValue = allowEdit; } /// <summary> /// Indicates whether or not the field/property allows editing of the /// value. /// </summary> /// <value> /// When <c>true</c>, the field/property is editable. /// <para> /// When <c>false</c>, the field/property is not editable. /// </para> /// </value> public bool AllowEdit { get; } /// <summary> /// Indicates whether or not the field/property allows an initial value /// to be specified. /// </summary> /// <remarks> /// The value of this property defaults to match the <see cref="AllowEdit" /> /// property value specified in the constructor. /// </remarks> /// <value> /// When <c>true</c>, the field/property can have its value set for /// newly constructed instances, such as during an insert operation. /// <para> /// When <c>false</c>, the field/property cannot have its /// value provided for newly constructed instances, such as during /// an insert operation. This will often indicate that the value /// is auto-generated by the persistence store. /// </para> /// </value> public bool AllowInitialValue { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.ComponentModel.DataAnnotations { /// <summary> /// Indicates whether the consumer of a field or property, such as a client application, /// should allow editing of the value. /// </summary> /// <remarks> /// This attribute neither enforces nor guarantees editability; the underlying data /// store might allow changing the data regardless of this attribute. The presence /// of this attribute signals intent to the consumer of the attribute whether or not /// the end user should be allowed to change the value via the client application. /// </remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class EditableAttribute : Attribute { /// <summary> /// Indicate whether or not a field/property is editable. /// </summary> /// <param name="allowEdit"> /// Indicates whether the field/property is editable. The value provided /// will apply to both <see cref="AllowEdit" /> and /// <see cref="AllowInitialValue" /> unless the <see cref="AllowInitialValue" /> /// property is explicitly specified. /// </param> public EditableAttribute(bool allowEdit) { AllowEdit = allowEdit; AllowInitialValue = allowEdit; } /// <summary> /// Indicates whether or not the field/property allows editing of the /// value. /// </summary> /// <value> /// When <c>true</c>, the field/property is editable. /// <para> /// When <c>false</c>, the field/property is not editable. /// </para> /// </value> public bool AllowEdit { get; } /// <summary> /// Indicates whether or not the field/property allows an initial value /// to be specified. /// </summary> /// <remarks> /// The value of this property defaults to match the <see cref="AllowEdit" /> /// property value specified in the constructor. /// </remarks> /// <value> /// When <c>true</c>, the field/property can have its value set for /// newly constructed instances, such as during an insert operation. /// <para> /// When <c>false</c>, the field/property cannot have its /// value provided for newly constructed instances, such as during /// an insert operation. This will often indicate that the value /// is auto-generated by the persistence store. /// </para> /// </value> public bool AllowInitialValue { get; set; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Threading { /// <summary> /// A LIFO semaphore. /// Waits on this semaphore are uninterruptible. /// </summary> internal sealed partial class LowLevelLifoSemaphore : IDisposable { private WaitSubsystem.WaitableObject _semaphore; private void Create(int maximumSignalCount) { _semaphore = WaitSubsystem.WaitableObject.NewSemaphore(0, maximumSignalCount); } public void Dispose() { } private bool WaitCore(int timeoutMs) { return WaitSubsystem.Wait(_semaphore, timeoutMs, false, true) == WaitHandle.WaitSuccess; } private void ReleaseCore(int count) { WaitSubsystem.ReleaseSemaphore(_semaphore, count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Threading { /// <summary> /// A LIFO semaphore. /// Waits on this semaphore are uninterruptible. /// </summary> internal sealed partial class LowLevelLifoSemaphore : IDisposable { private WaitSubsystem.WaitableObject _semaphore; private void Create(int maximumSignalCount) { _semaphore = WaitSubsystem.WaitableObject.NewSemaphore(0, maximumSignalCount); } public void Dispose() { } private bool WaitCore(int timeoutMs) { return WaitSubsystem.Wait(_semaphore, timeoutMs, false, true) == WaitHandle.WaitSuccess; } private void ReleaseCore(int count) { WaitSubsystem.ReleaseSemaphore(_semaphore, count); } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Methodical/Arrays/lcs/lcsval.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace JitTest { internal struct Data { public int b, c; }; internal class LCS { private const int RANK = 4; private static String buildLCS(Data[,,,] mtx, char[] X, int[] ind) { for (int i = 0; i < RANK; i++) if (ind[i] == 0) return ""; int L = mtx[ind[0], ind[1], ind[2], ind[3]].b; if (L == RANK) { for (int i = 0; i < RANK; i++) ind[i]--; int idx = ind[0]; return buildLCS(mtx, X, ind) + X[idx]; } if (L >= 0 && L < RANK) { ind[L]--; return buildLCS(mtx, X, ind); } throw new Exception(); } private static void findLCS(Data[,,,] mtx, char[][] seq, int[] len) { int[] ind = new int[RANK]; for (ind[0] = 1; ind[0] < len[0]; ind[0]++) { for (ind[1] = 1; ind[1] < len[1]; ind[1]++) { for (ind[2] = 1; ind[2] < len[2]; ind[2]++) { for (ind[3] = 1; ind[3] < len[3]; ind[3]++) { bool eqFlag = true; for (int i = 1; i < RANK; i++) { if (seq[i][ind[i] - 1] != seq[i - 1][ind[i - 1] - 1]) { eqFlag = false; break; } } if (eqFlag) { mtx[ind[0], ind[1], ind[2], ind[3]].c = mtx[ind[0] - 1, ind[1] - 1, ind[2] - 1, ind[3] - 1].c + 1; mtx[ind[0], ind[1], ind[2], ind[3]].b = RANK; continue; } int R = -1; int M = -1; for (int i = 0; i < RANK; i++) { ind[i]--; if (mtx[ind[0], ind[1], ind[2], ind[3]].c > M) { R = i; M = mtx[ind[0], ind[1], ind[2], ind[3]].c; } ind[i]++; } if (R < 0 || M < 0) throw new Exception(); mtx[ind[0], ind[1], ind[2], ind[3]].c = M; mtx[ind[0], ind[1], ind[2], ind[3]].b = R; } } } } } private static int Main() { Console.WriteLine("Test searches for longest common subsequence of 4 strings\n\n"); String[] str = new String[RANK] { "The Sun has left his blackness", "and has found a fresher morning", "and the fair Moon rejoices", "in the clear and cloudless night" }; int[] len = new int[RANK]; char[][] seq = new char[RANK][]; for (int i = 0; i < RANK; i++) { len[i] = str[i].Length + 1; seq[i] = str[i].ToCharArray(); } Data[,,,] mtx = new Data[len[0], len[1], len[2], len[3]]; findLCS(mtx, seq, len); for (int i = 0; i < RANK; i++) len[i]--; if ("n ha es" == buildLCS(mtx, seq[0], len)) { Console.WriteLine("Test passed"); return 100; } else { Console.WriteLine("Test failed."); return 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace JitTest { internal struct Data { public int b, c; }; internal class LCS { private const int RANK = 4; private static String buildLCS(Data[,,,] mtx, char[] X, int[] ind) { for (int i = 0; i < RANK; i++) if (ind[i] == 0) return ""; int L = mtx[ind[0], ind[1], ind[2], ind[3]].b; if (L == RANK) { for (int i = 0; i < RANK; i++) ind[i]--; int idx = ind[0]; return buildLCS(mtx, X, ind) + X[idx]; } if (L >= 0 && L < RANK) { ind[L]--; return buildLCS(mtx, X, ind); } throw new Exception(); } private static void findLCS(Data[,,,] mtx, char[][] seq, int[] len) { int[] ind = new int[RANK]; for (ind[0] = 1; ind[0] < len[0]; ind[0]++) { for (ind[1] = 1; ind[1] < len[1]; ind[1]++) { for (ind[2] = 1; ind[2] < len[2]; ind[2]++) { for (ind[3] = 1; ind[3] < len[3]; ind[3]++) { bool eqFlag = true; for (int i = 1; i < RANK; i++) { if (seq[i][ind[i] - 1] != seq[i - 1][ind[i - 1] - 1]) { eqFlag = false; break; } } if (eqFlag) { mtx[ind[0], ind[1], ind[2], ind[3]].c = mtx[ind[0] - 1, ind[1] - 1, ind[2] - 1, ind[3] - 1].c + 1; mtx[ind[0], ind[1], ind[2], ind[3]].b = RANK; continue; } int R = -1; int M = -1; for (int i = 0; i < RANK; i++) { ind[i]--; if (mtx[ind[0], ind[1], ind[2], ind[3]].c > M) { R = i; M = mtx[ind[0], ind[1], ind[2], ind[3]].c; } ind[i]++; } if (R < 0 || M < 0) throw new Exception(); mtx[ind[0], ind[1], ind[2], ind[3]].c = M; mtx[ind[0], ind[1], ind[2], ind[3]].b = R; } } } } } private static int Main() { Console.WriteLine("Test searches for longest common subsequence of 4 strings\n\n"); String[] str = new String[RANK] { "The Sun has left his blackness", "and has found a fresher morning", "and the fair Moon rejoices", "in the clear and cloudless night" }; int[] len = new int[RANK]; char[][] seq = new char[RANK][]; for (int i = 0; i < RANK; i++) { len[i] = str[i].Length + 1; seq[i] = str[i].ToCharArray(); } Data[,,,] mtx = new Data[len[0], len[1], len[2], len[3]]; findLCS(mtx, seq, len); for (int i = 0; i < RANK; i++) len[i]--; if ("n ha es" == buildLCS(mtx, seq[0], len)) { Console.WriteLine("Test passed"); return 100; } else { Console.WriteLine("Test failed."); return 0; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/Interop/PInvoke/Varargs/VarargsTest.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.Security; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using Xunit; namespace PInvokeTests { class VarargsTest { [DllImport("VarargsNative", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] private static extern void TestVarArgs(StringBuilder builder, IntPtr bufferSize, string formatString, __arglist); [DllImport("VarargsNative", CharSet = CharSet.Unicode)] private static extern void TestArgIterator(StringBuilder builder, IntPtr bufferSize, string formatString, ArgIterator arguments); private static void TestArgIteratorWrapper(StringBuilder builder, IntPtr bufferSize, string formatString, __arglist) { TestArgIterator(builder, bufferSize, formatString, new ArgIterator(__arglist)); } private static bool AssertEqual(string lhs, string rhs) { if (lhs != rhs) { Console.WriteLine($"FAIL! \"{lhs}\" != \"{rhs}\""); return false; } return true; } public static int Main() { var passed = true; int arg1 = 10; int arg2 = 20; double arg3 = 12.5; string expected = FormattableString.Invariant($"{arg1}, {arg2}, {arg3:F1}"); StringBuilder builder; builder = new StringBuilder(30); TestVarArgs(builder, (IntPtr)30, "%i, %i, %.1f", __arglist(arg1, arg2, arg3)); passed &= AssertEqual(builder.ToString(), expected); builder = new StringBuilder(30); TestArgIteratorWrapper(builder, (IntPtr)30, "%i, %i, %.1f", __arglist(arg1, arg2, arg3)); passed &= AssertEqual(builder.ToString(), expected); return passed ? 100 : 101; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Security; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using Xunit; namespace PInvokeTests { class VarargsTest { [DllImport("VarargsNative", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] private static extern void TestVarArgs(StringBuilder builder, IntPtr bufferSize, string formatString, __arglist); [DllImport("VarargsNative", CharSet = CharSet.Unicode)] private static extern void TestArgIterator(StringBuilder builder, IntPtr bufferSize, string formatString, ArgIterator arguments); private static void TestArgIteratorWrapper(StringBuilder builder, IntPtr bufferSize, string formatString, __arglist) { TestArgIterator(builder, bufferSize, formatString, new ArgIterator(__arglist)); } private static bool AssertEqual(string lhs, string rhs) { if (lhs != rhs) { Console.WriteLine($"FAIL! \"{lhs}\" != \"{rhs}\""); return false; } return true; } public static int Main() { var passed = true; int arg1 = 10; int arg2 = 20; double arg3 = 12.5; string expected = FormattableString.Invariant($"{arg1}, {arg2}, {arg3:F1}"); StringBuilder builder; builder = new StringBuilder(30); TestVarArgs(builder, (IntPtr)30, "%i, %i, %.1f", __arglist(arg1, arg2, arg3)); passed &= AssertEqual(builder.ToString(), expected); builder = new StringBuilder(30); TestArgIteratorWrapper(builder, (IntPtr)30, "%i, %i, %.1f", __arglist(arg1, arg2, arg3)); passed &= AssertEqual(builder.ToString(), expected); return passed ? 100 : 101; } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/Interop/IJW/FixupCallsHostWhenLoaded/FixupCallsHostWhenLoaded.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; using System.Reflection; using System.Runtime.InteropServices; using Xunit; namespace FixupCallsHostWhenLoaded { class FixupCallsHostWhenLoaded { static int Main(string[] args) { // Disable running on Windows 7 until IJW activation work is complete. if(Environment.OSVersion.Platform != PlatformID.Win32NT || TestLibrary.Utilities.IsWindows7) { return 100; } try { IntPtr ijwHost = NativeLibrary.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ijwhost.dll")); WasModuleVTableQueriedDelegate wasModuleVTableQueried = Marshal.GetDelegateForFunctionPointer<WasModuleVTableQueriedDelegate>(NativeLibrary.GetExport(ijwHost, "WasModuleVTableQueried")); // Load IJW via reflection Assembly.Load("IjwNativeDll"); IntPtr ijwModuleHandle = GetModuleHandle("IjwNativeDll.dll"); Assert.NotEqual(IntPtr.Zero, ijwModuleHandle); Assert.True(wasModuleVTableQueried(ijwModuleHandle)); } catch (Exception e) { Console.WriteLine(e); return 101; } return 100; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate bool WasModuleVTableQueriedDelegate(IntPtr handle); [DllImport("kernel32.dll")] static extern IntPtr GetModuleHandle(string lpModuleName); } }
// 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; using System.Reflection; using System.Runtime.InteropServices; using Xunit; namespace FixupCallsHostWhenLoaded { class FixupCallsHostWhenLoaded { static int Main(string[] args) { // Disable running on Windows 7 until IJW activation work is complete. if(Environment.OSVersion.Platform != PlatformID.Win32NT || TestLibrary.Utilities.IsWindows7) { return 100; } try { IntPtr ijwHost = NativeLibrary.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ijwhost.dll")); WasModuleVTableQueriedDelegate wasModuleVTableQueried = Marshal.GetDelegateForFunctionPointer<WasModuleVTableQueriedDelegate>(NativeLibrary.GetExport(ijwHost, "WasModuleVTableQueried")); // Load IJW via reflection Assembly.Load("IjwNativeDll"); IntPtr ijwModuleHandle = GetModuleHandle("IjwNativeDll.dll"); Assert.NotEqual(IntPtr.Zero, ijwModuleHandle); Assert.True(wasModuleVTableQueried(ijwModuleHandle)); } catch (Exception e) { Console.WriteLine(e); return 101; } return 100; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate bool WasModuleVTableQueriedDelegate(IntPtr handle); [DllImport("kernel32.dll")] static extern IntPtr GetModuleHandle(string lpModuleName); } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/DateTimeHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Text; namespace System.ServiceModel.Syndication { internal static class DateTimeHelper { private const string Rfc3339DateTimeFormat = "yyyy-MM-ddTHH:mm:ssK"; public static bool DefaultRss20DateTimeParser(XmlDateTimeData XmlDateTimeData, out DateTimeOffset dateTimeOffset) { string dateTimeString = XmlDateTimeData.DateTimeString; // First check if DateTimeOffset default parsing can parse the date if (DateTimeOffset.TryParse(dateTimeString, out dateTimeOffset)) { return true; } // RSS specifies RFC822 if (Rfc822DateTimeParser(dateTimeString, out dateTimeOffset)) { return true; } // Event though RCS3339 is for Atom, someone might be using this for RSS if (Rfc3339DateTimeParser(dateTimeString, out dateTimeOffset)) { return true; } return false; } public static bool DefaultAtom10DateTimeParser(XmlDateTimeData XmlDateTimeData, out DateTimeOffset dateTimeOffset) { return Rfc3339DateTimeParser(XmlDateTimeData.DateTimeString, out dateTimeOffset); } private static bool Rfc3339DateTimeParser(string dateTimeString, out DateTimeOffset dto) { dto = default(DateTimeOffset); dateTimeString = dateTimeString.Trim(); if (dateTimeString.Length < 20) { return false; } if (dateTimeString[19] == '.') { // remove any fractional seconds, we choose to ignore them int i = 20; while (dateTimeString.Length > i && char.IsDigit(dateTimeString[i])) { ++i; } dateTimeString = dateTimeString.Substring(0, 19) + dateTimeString.Substring(i); } return DateTimeOffset.TryParseExact(dateTimeString, Rfc3339DateTimeFormat, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dto); } private static bool Rfc822DateTimeParser(string dateTimeString, out DateTimeOffset dto) { dto = default(DateTimeOffset); StringBuilder dateTimeStringBuilder = new StringBuilder(dateTimeString.Trim()); if (dateTimeStringBuilder.Length < 18) { return false; } int timeZoneStartIndex; for (timeZoneStartIndex = dateTimeStringBuilder.Length - 1; dateTimeStringBuilder[timeZoneStartIndex] != ' '; timeZoneStartIndex--) ; timeZoneStartIndex++; int timeZoneLength = dateTimeStringBuilder.Length - timeZoneStartIndex; string timeZoneSuffix = dateTimeStringBuilder.ToString(timeZoneStartIndex, timeZoneLength); dateTimeStringBuilder.Remove(timeZoneStartIndex, timeZoneLength); bool isUtc; dateTimeStringBuilder.Append(NormalizeTimeZone(timeZoneSuffix, out isUtc)); string wellFormattedString = dateTimeStringBuilder.ToString(); DateTimeOffset theTime; string[] parseFormat = { "ddd, dd MMMM yyyy HH:mm:ss zzz", "dd MMMM yyyy HH:mm:ss zzz", "ddd, dd MMM yyyy HH:mm:ss zzz", "dd MMM yyyy HH:mm:ss zzz", "ddd, dd MMMM yyyy HH:mm zzz", "dd MMMM yyyy HH:mm zzz", "ddd, dd MMM yyyy HH:mm zzz", "dd MMM yyyy HH:mm zzz", // The original RFC822 spec listed 2 digit years. RFC1123 updated the format to include 4 digit years and states that you should use 4 digits. // Technically RSS2.0 specifies RFC822 but it's presumed that RFC1123 will be used as we're now past Y2K and everyone knows better. The 4 digit // formats are listed first for performance reasons as it's presumed they will be more likely to match first. "ddd, dd MMMM yy HH:mm:ss zzz", "dd MMMM yyyy HH:mm:ss zzz", "ddd, dd MMM yy HH:mm:ss zzz", "dd MMM yyyy HH:mm:ss zzz", "ddd, dd MMMM yy HH:mm zzz", "dd MMMM yyyy HH:mm zzz", "ddd, dd MMM yy HH:mm zzz", "dd MMM yyyy HH:mm zzz" }; if (DateTimeOffset.TryParseExact(wellFormattedString, parseFormat, CultureInfo.InvariantCulture.DateTimeFormat, (isUtc ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None), out theTime)) { dto = theTime; return true; } return false; } private static string NormalizeTimeZone(string rfc822TimeZone, out bool isUtc) { isUtc = false; // return a string in "-08:00" format if (rfc822TimeZone[0] == '+' || rfc822TimeZone[0] == '-') { // the time zone is supposed to be 4 digits but some feeds omit the initial 0 StringBuilder result = new StringBuilder(rfc822TimeZone); if (result.Length == 4) { // the timezone is +/-HMM. Convert to +/-HHMM result.Insert(1, '0'); } result.Insert(3, ':'); return result.ToString(); } switch (rfc822TimeZone) { case "UT": case "Z": isUtc = true; return "-00:00"; case "GMT": return "-00:00"; case "A": return "-01:00"; case "B": return "-02:00"; case "C": return "-03:00"; case "D": case "EDT": return "-04:00"; case "E": case "EST": case "CDT": return "-05:00"; case "F": case "CST": case "MDT": return "-06:00"; case "G": case "MST": case "PDT": return "-07:00"; case "H": case "PST": return "-08:00"; case "I": return "-09:00"; case "K": return "-10:00"; case "L": return "-11:00"; case "M": return "-12:00"; case "N": return "+01:00"; case "O": return "+02:00"; case "P": return "+03:00"; case "Q": return "+04:00"; case "R": return "+05:00"; case "S": return "+06:00"; case "T": return "+07:00"; case "U": return "+08:00"; case "V": return "+09:00"; case "W": return "+10:00"; case "X": return "+11:00"; case "Y": return "+12:00"; default: return ""; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Text; namespace System.ServiceModel.Syndication { internal static class DateTimeHelper { private const string Rfc3339DateTimeFormat = "yyyy-MM-ddTHH:mm:ssK"; public static bool DefaultRss20DateTimeParser(XmlDateTimeData XmlDateTimeData, out DateTimeOffset dateTimeOffset) { string dateTimeString = XmlDateTimeData.DateTimeString; // First check if DateTimeOffset default parsing can parse the date if (DateTimeOffset.TryParse(dateTimeString, out dateTimeOffset)) { return true; } // RSS specifies RFC822 if (Rfc822DateTimeParser(dateTimeString, out dateTimeOffset)) { return true; } // Event though RCS3339 is for Atom, someone might be using this for RSS if (Rfc3339DateTimeParser(dateTimeString, out dateTimeOffset)) { return true; } return false; } public static bool DefaultAtom10DateTimeParser(XmlDateTimeData XmlDateTimeData, out DateTimeOffset dateTimeOffset) { return Rfc3339DateTimeParser(XmlDateTimeData.DateTimeString, out dateTimeOffset); } private static bool Rfc3339DateTimeParser(string dateTimeString, out DateTimeOffset dto) { dto = default(DateTimeOffset); dateTimeString = dateTimeString.Trim(); if (dateTimeString.Length < 20) { return false; } if (dateTimeString[19] == '.') { // remove any fractional seconds, we choose to ignore them int i = 20; while (dateTimeString.Length > i && char.IsDigit(dateTimeString[i])) { ++i; } dateTimeString = dateTimeString.Substring(0, 19) + dateTimeString.Substring(i); } return DateTimeOffset.TryParseExact(dateTimeString, Rfc3339DateTimeFormat, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dto); } private static bool Rfc822DateTimeParser(string dateTimeString, out DateTimeOffset dto) { dto = default(DateTimeOffset); StringBuilder dateTimeStringBuilder = new StringBuilder(dateTimeString.Trim()); if (dateTimeStringBuilder.Length < 18) { return false; } int timeZoneStartIndex; for (timeZoneStartIndex = dateTimeStringBuilder.Length - 1; dateTimeStringBuilder[timeZoneStartIndex] != ' '; timeZoneStartIndex--) ; timeZoneStartIndex++; int timeZoneLength = dateTimeStringBuilder.Length - timeZoneStartIndex; string timeZoneSuffix = dateTimeStringBuilder.ToString(timeZoneStartIndex, timeZoneLength); dateTimeStringBuilder.Remove(timeZoneStartIndex, timeZoneLength); bool isUtc; dateTimeStringBuilder.Append(NormalizeTimeZone(timeZoneSuffix, out isUtc)); string wellFormattedString = dateTimeStringBuilder.ToString(); DateTimeOffset theTime; string[] parseFormat = { "ddd, dd MMMM yyyy HH:mm:ss zzz", "dd MMMM yyyy HH:mm:ss zzz", "ddd, dd MMM yyyy HH:mm:ss zzz", "dd MMM yyyy HH:mm:ss zzz", "ddd, dd MMMM yyyy HH:mm zzz", "dd MMMM yyyy HH:mm zzz", "ddd, dd MMM yyyy HH:mm zzz", "dd MMM yyyy HH:mm zzz", // The original RFC822 spec listed 2 digit years. RFC1123 updated the format to include 4 digit years and states that you should use 4 digits. // Technically RSS2.0 specifies RFC822 but it's presumed that RFC1123 will be used as we're now past Y2K and everyone knows better. The 4 digit // formats are listed first for performance reasons as it's presumed they will be more likely to match first. "ddd, dd MMMM yy HH:mm:ss zzz", "dd MMMM yyyy HH:mm:ss zzz", "ddd, dd MMM yy HH:mm:ss zzz", "dd MMM yyyy HH:mm:ss zzz", "ddd, dd MMMM yy HH:mm zzz", "dd MMMM yyyy HH:mm zzz", "ddd, dd MMM yy HH:mm zzz", "dd MMM yyyy HH:mm zzz" }; if (DateTimeOffset.TryParseExact(wellFormattedString, parseFormat, CultureInfo.InvariantCulture.DateTimeFormat, (isUtc ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None), out theTime)) { dto = theTime; return true; } return false; } private static string NormalizeTimeZone(string rfc822TimeZone, out bool isUtc) { isUtc = false; // return a string in "-08:00" format if (rfc822TimeZone[0] == '+' || rfc822TimeZone[0] == '-') { // the time zone is supposed to be 4 digits but some feeds omit the initial 0 StringBuilder result = new StringBuilder(rfc822TimeZone); if (result.Length == 4) { // the timezone is +/-HMM. Convert to +/-HHMM result.Insert(1, '0'); } result.Insert(3, ':'); return result.ToString(); } switch (rfc822TimeZone) { case "UT": case "Z": isUtc = true; return "-00:00"; case "GMT": return "-00:00"; case "A": return "-01:00"; case "B": return "-02:00"; case "C": return "-03:00"; case "D": case "EDT": return "-04:00"; case "E": case "EST": case "CDT": return "-05:00"; case "F": case "CST": case "MDT": return "-06:00"; case "G": case "MST": case "PDT": return "-07:00"; case "H": case "PST": return "-08:00"; case "I": return "-09:00"; case "K": return "-10:00"; case "L": return "-11:00"; case "M": return "-12:00"; case "N": return "+01:00"; case "O": return "+02:00"; case "P": return "+03:00"; case "Q": return "+04:00"; case "R": return "+05:00"; case "S": return "+06:00"; case "T": return "+07:00"; case "U": return "+08:00"; case "V": return "+09:00"; case "W": return "+10:00"; case "X": return "+11:00"; case "Y": return "+12:00"; default: return ""; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Runtime/tests/System/ExitCodeTests.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Tests { public class ExitCodeTests { private const int SIGTERM = 15; [DllImport("libc", SetLastError = true)] private static extern int kill(int pid, int sig); [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/31656", TestRuntimes.Mono)] [InlineData(null)] [InlineData(0)] [InlineData(42)] [PlatformSpecific(TestPlatforms.AnyUnix)] // SIGTERM signal. public void SigTermExitCode(int? exitCodeOnSigterm) { Action<string> action = (string sigTermExitCode) => { if (!string.IsNullOrEmpty(sigTermExitCode)) { AppDomain.CurrentDomain.ProcessExit += (sender, args) => { Assert.Same(AppDomain.CurrentDomain, sender); Environment.ExitCode = int.Parse(sigTermExitCode); }; } Console.WriteLine("Application started"); // Wait for SIGTERM System.Threading.Thread.Sleep(int.MaxValue); }; RemoteInvokeOptions options = new RemoteInvokeOptions(); options.StartInfo.RedirectStandardOutput = true; options.CheckExitCode = false; using (RemoteInvokeHandle remoteExecution = RemoteExecutor.Invoke(action, exitCodeOnSigterm?.ToString() ?? string.Empty, options)) { Process process = remoteExecution.Process; // Wait for the process to start and register the ProcessExit handler string processOutput = process.StandardOutput.ReadLine(); Assert.Equal("Application started", processOutput); // Send SIGTERM int rv = kill(process.Id, SIGTERM); Assert.Equal(0, rv); // Process exits in a timely manner bool exited = process.WaitForExit(RemoteExecutor.FailWaitTimeoutMilliseconds); Assert.True(exited); // Check exit code Assert.Equal(exitCodeOnSigterm ?? 128 + SIGTERM, process.ExitCode); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Tests { public class ExitCodeTests { private const int SIGTERM = 15; [DllImport("libc", SetLastError = true)] private static extern int kill(int pid, int sig); [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/31656", TestRuntimes.Mono)] [InlineData(null)] [InlineData(0)] [InlineData(42)] [PlatformSpecific(TestPlatforms.AnyUnix)] // SIGTERM signal. public void SigTermExitCode(int? exitCodeOnSigterm) { Action<string> action = (string sigTermExitCode) => { if (!string.IsNullOrEmpty(sigTermExitCode)) { AppDomain.CurrentDomain.ProcessExit += (sender, args) => { Assert.Same(AppDomain.CurrentDomain, sender); Environment.ExitCode = int.Parse(sigTermExitCode); }; } Console.WriteLine("Application started"); // Wait for SIGTERM System.Threading.Thread.Sleep(int.MaxValue); }; RemoteInvokeOptions options = new RemoteInvokeOptions(); options.StartInfo.RedirectStandardOutput = true; options.CheckExitCode = false; using (RemoteInvokeHandle remoteExecution = RemoteExecutor.Invoke(action, exitCodeOnSigterm?.ToString() ?? string.Empty, options)) { Process process = remoteExecution.Process; // Wait for the process to start and register the ProcessExit handler string processOutput = process.StandardOutput.ReadLine(); Assert.Equal("Application started", processOutput); // Send SIGTERM int rv = kill(process.Id, SIGTERM); Assert.Equal(0, rv); // Process exits in a timely manner bool exited = process.WaitForExit(RemoteExecutor.FailWaitTimeoutMilliseconds); Assert.True(exited); // Check exit code Assert.Equal(exitCodeOnSigterm ?? 128 + SIGTERM, process.ExitCode); } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/General/Vector64/GreaterThanAny.Int16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 GreaterThanAnyInt16() { var test = new VectorBooleanBinaryOpTest__GreaterThanAnyInt16(); // 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__GreaterThanAnyInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanAnyInt16 testClass) { var result = Vector64.GreaterThanAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanAnyInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public VectorBooleanBinaryOpTest__GreaterThanAnyInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.GreaterThanAny( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanAny), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanAny), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.GreaterThanAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = Vector64.GreaterThanAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanAnyInt16(); var result = Vector64.GreaterThanAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.GreaterThanAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.GreaterThanAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] 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(Vector64)}.{nameof(Vector64.GreaterThanAny)}<Int16>(Vector64<Int16>, Vector64<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({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 GreaterThanAnyInt16() { var test = new VectorBooleanBinaryOpTest__GreaterThanAnyInt16(); // 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__GreaterThanAnyInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanAnyInt16 testClass) { var result = Vector64.GreaterThanAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanAnyInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public VectorBooleanBinaryOpTest__GreaterThanAnyInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.GreaterThanAny( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanAny), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.GreaterThanAny), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.GreaterThanAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = Vector64.GreaterThanAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanAnyInt16(); var result = Vector64.GreaterThanAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.GreaterThanAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.GreaterThanAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] 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(Vector64)}.{nameof(Vector64.GreaterThanAny)}<Int16>(Vector64<Int16>, Vector64<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/StackSpiller.Temps.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; namespace System.Linq.Expressions.Compiler { internal sealed partial class StackSpiller { /// <summary> /// The source of temporary variables introduced during stack spilling. /// </summary> private readonly TempMaker _tm = new TempMaker(); /// <summary> /// Creates a temporary variable of the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type for the temporary variable to create.</param> /// <returns> /// A temporary variable of the specified <paramref name="type"/>. When the temporary /// variable is no longer used, it should be returned by using the <see cref="Mark"/> /// and <see cref="Free"/> mechanism provided. /// </returns> private ParameterExpression MakeTemp(Type type) => _tm.Temp(type); /// <summary> /// Gets a watermark into the stack of used temporary variables. The returned /// watermark value can be passed to <see cref="Free"/> to free all variables /// below the watermark value, allowing them to be reused. /// </summary> /// <returns> /// A watermark value indicating the number of temporary variables currently in use. /// </returns> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> private int Mark() => _tm.Mark(); /// <summary> /// Frees temporaries created since the last marking using <see cref="Mark"/>. /// </summary> /// <param name="mark">The watermark value up to which to recycle used temporary variables.</param> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> private void Free(int mark) => _tm.Free(mark); /// <summary> /// Verifies that all temporary variables get properly returned to the free list /// after stack spilling for a lambda expression has taken place. This is used /// to detect misuse of the <see cref="Mark"/> and <see cref="Free"/> methods. /// </summary> [Conditional("DEBUG")] private void VerifyTemps() => _tm.VerifyTemps(); /// <summary> /// Creates and returns a temporary variable to store the result of evaluating /// the specified <paramref name="expression"/>. /// </summary> /// <param name="expression">The expression to store in a temporary variable.</param> /// <param name="save">An expression that assigns the <paramref name="expression"/> to the created temporary variable.</param> /// <param name="byRef">Indicates whether the <paramref name="expression"/> represents a ByRef value.</param> /// <returns>The temporary variable holding the result of evaluating <paramref name="expression"/>.</returns> private ParameterExpression ToTemp(Expression expression, out Expression save, bool byRef) { Type tempType = byRef ? expression.Type.MakeByRefType() : expression.Type; ParameterExpression temp = MakeTemp(tempType); save = AssignBinaryExpression.Make(temp, expression, byRef); return temp; } /// <summary> /// Utility to create and recycle temporary variables. /// </summary> private sealed class TempMaker { /// <summary> /// Index of the next temporary variable to create. /// This value is used for naming temporary variables using an increasing index. /// </summary> private int _temp; /// <summary> /// List of free temporary variables. These can be recycled for new temporary variables. /// </summary> private List<ParameterExpression>? _freeTemps; /// <summary> /// Stack of temporary variables that are currently in use. /// </summary> private Stack<ParameterExpression>? _usedTemps; /// <summary> /// List of all temporary variables created by the stack spiller instance. /// </summary> internal List<ParameterExpression> Temps { get; } = new List<ParameterExpression>(); /// <summary> /// Creates a temporary variable of the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type for the temporary variable to create.</param> /// <returns> /// A temporary variable of the specified <paramref name="type"/>. When the temporary /// variable is no longer used, it should be returned by using the <see cref="Mark"/> /// and <see cref="Free"/> mechanism provided. /// </returns> internal ParameterExpression Temp(Type type) { ParameterExpression temp; if (_freeTemps != null) { // Recycle from the free-list if possible. for (int i = _freeTemps.Count - 1; i >= 0; i--) { temp = _freeTemps[i]; if (temp.Type == type) { _freeTemps.RemoveAt(i); return UseTemp(temp); } } } // Not on the free-list, create a brand new one. temp = ParameterExpression.Make(type, "$temp$" + _temp++, isByRef: false); Temps.Add(temp); return UseTemp(temp); } /// <summary> /// Registers the temporary variable in the stack of used temporary variables. /// The <see cref="Mark"/> and <see cref="Free"/> methods use a watermark index /// into this stack to enable recycling temporary variables in bulk. /// </summary> /// <param name="temp">The temporary variable to mark as used.</param> /// <returns>The original temporary variable.</returns> private ParameterExpression UseTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp)); if (_usedTemps == null) { _usedTemps = new Stack<ParameterExpression>(); } _usedTemps.Push(temp); return temp; } /// <summary> /// Puts the temporary variable on the free list which is used by the /// <see cref="Temp"/> method to reuse temporary variables. /// </summary> /// <param name="temp">The temporary variable to mark as no longer in use.</param> private void FreeTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); if (_freeTemps == null) { _freeTemps = new List<ParameterExpression>(); } _freeTemps.Add(temp); } /// <summary> /// Gets a watermark into the stack of used temporary variables. The returned /// watermark value can be passed to <see cref="Free"/> to free all variables /// below the watermark value, allowing them to be reused. /// </summary> /// <returns> /// A watermark value indicating the number of temporary variables currently in use. /// </returns> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> internal int Mark() => _usedTemps?.Count ?? 0; /// <summary> /// Frees temporaries created since the last marking using <see cref="Mark"/>. /// </summary> /// <param name="mark">The watermark value up to which to recycle used temporary variables.</param> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> internal void Free(int mark) { // (_usedTemps != null) ==> (mark <= _usedTemps.Count) Debug.Assert(_usedTemps == null || mark <= _usedTemps.Count); // (_usedTemps == null) ==> (mark == 0) Debug.Assert(mark == 0 || _usedTemps != null); if (_usedTemps != null) { while (mark < _usedTemps.Count) { FreeTemp(_usedTemps.Pop()); } } } /// <summary> /// Verifies that all temporary variables get properly returned to the free list /// after stack spilling for a lambda expression has taken place. This is used /// to detect misuse of the <see cref="Mark"/> and <see cref="Free"/> methods. /// </summary> [Conditional("DEBUG")] internal void VerifyTemps() { Debug.Assert(_usedTemps == null || _usedTemps.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 System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Linq.Expressions.Compiler { internal sealed partial class StackSpiller { /// <summary> /// The source of temporary variables introduced during stack spilling. /// </summary> private readonly TempMaker _tm = new TempMaker(); /// <summary> /// Creates a temporary variable of the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type for the temporary variable to create.</param> /// <returns> /// A temporary variable of the specified <paramref name="type"/>. When the temporary /// variable is no longer used, it should be returned by using the <see cref="Mark"/> /// and <see cref="Free"/> mechanism provided. /// </returns> private ParameterExpression MakeTemp(Type type) => _tm.Temp(type); /// <summary> /// Gets a watermark into the stack of used temporary variables. The returned /// watermark value can be passed to <see cref="Free"/> to free all variables /// below the watermark value, allowing them to be reused. /// </summary> /// <returns> /// A watermark value indicating the number of temporary variables currently in use. /// </returns> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> private int Mark() => _tm.Mark(); /// <summary> /// Frees temporaries created since the last marking using <see cref="Mark"/>. /// </summary> /// <param name="mark">The watermark value up to which to recycle used temporary variables.</param> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> private void Free(int mark) => _tm.Free(mark); /// <summary> /// Verifies that all temporary variables get properly returned to the free list /// after stack spilling for a lambda expression has taken place. This is used /// to detect misuse of the <see cref="Mark"/> and <see cref="Free"/> methods. /// </summary> [Conditional("DEBUG")] private void VerifyTemps() => _tm.VerifyTemps(); /// <summary> /// Creates and returns a temporary variable to store the result of evaluating /// the specified <paramref name="expression"/>. /// </summary> /// <param name="expression">The expression to store in a temporary variable.</param> /// <param name="save">An expression that assigns the <paramref name="expression"/> to the created temporary variable.</param> /// <param name="byRef">Indicates whether the <paramref name="expression"/> represents a ByRef value.</param> /// <returns>The temporary variable holding the result of evaluating <paramref name="expression"/>.</returns> private ParameterExpression ToTemp(Expression expression, out Expression save, bool byRef) { Type tempType = byRef ? expression.Type.MakeByRefType() : expression.Type; ParameterExpression temp = MakeTemp(tempType); save = AssignBinaryExpression.Make(temp, expression, byRef); return temp; } /// <summary> /// Utility to create and recycle temporary variables. /// </summary> private sealed class TempMaker { /// <summary> /// Index of the next temporary variable to create. /// This value is used for naming temporary variables using an increasing index. /// </summary> private int _temp; /// <summary> /// List of free temporary variables. These can be recycled for new temporary variables. /// </summary> private List<ParameterExpression>? _freeTemps; /// <summary> /// Stack of temporary variables that are currently in use. /// </summary> private Stack<ParameterExpression>? _usedTemps; /// <summary> /// List of all temporary variables created by the stack spiller instance. /// </summary> internal List<ParameterExpression> Temps { get; } = new List<ParameterExpression>(); /// <summary> /// Creates a temporary variable of the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type for the temporary variable to create.</param> /// <returns> /// A temporary variable of the specified <paramref name="type"/>. When the temporary /// variable is no longer used, it should be returned by using the <see cref="Mark"/> /// and <see cref="Free"/> mechanism provided. /// </returns> internal ParameterExpression Temp(Type type) { ParameterExpression temp; if (_freeTemps != null) { // Recycle from the free-list if possible. for (int i = _freeTemps.Count - 1; i >= 0; i--) { temp = _freeTemps[i]; if (temp.Type == type) { _freeTemps.RemoveAt(i); return UseTemp(temp); } } } // Not on the free-list, create a brand new one. temp = ParameterExpression.Make(type, "$temp$" + _temp++, isByRef: false); Temps.Add(temp); return UseTemp(temp); } /// <summary> /// Registers the temporary variable in the stack of used temporary variables. /// The <see cref="Mark"/> and <see cref="Free"/> methods use a watermark index /// into this stack to enable recycling temporary variables in bulk. /// </summary> /// <param name="temp">The temporary variable to mark as used.</param> /// <returns>The original temporary variable.</returns> private ParameterExpression UseTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp)); if (_usedTemps == null) { _usedTemps = new Stack<ParameterExpression>(); } _usedTemps.Push(temp); return temp; } /// <summary> /// Puts the temporary variable on the free list which is used by the /// <see cref="Temp"/> method to reuse temporary variables. /// </summary> /// <param name="temp">The temporary variable to mark as no longer in use.</param> private void FreeTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); if (_freeTemps == null) { _freeTemps = new List<ParameterExpression>(); } _freeTemps.Add(temp); } /// <summary> /// Gets a watermark into the stack of used temporary variables. The returned /// watermark value can be passed to <see cref="Free"/> to free all variables /// below the watermark value, allowing them to be reused. /// </summary> /// <returns> /// A watermark value indicating the number of temporary variables currently in use. /// </returns> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> internal int Mark() => _usedTemps?.Count ?? 0; /// <summary> /// Frees temporaries created since the last marking using <see cref="Mark"/>. /// </summary> /// <param name="mark">The watermark value up to which to recycle used temporary variables.</param> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> internal void Free(int mark) { // (_usedTemps != null) ==> (mark <= _usedTemps.Count) Debug.Assert(_usedTemps == null || mark <= _usedTemps.Count); // (_usedTemps == null) ==> (mark == 0) Debug.Assert(mark == 0 || _usedTemps != null); if (_usedTemps != null) { while (mark < _usedTemps.Count) { FreeTemp(_usedTemps.Pop()); } } } /// <summary> /// Verifies that all temporary variables get properly returned to the free list /// after stack spilling for a lambda expression has taken place. This is used /// to detect misuse of the <see cref="Mark"/> and <see cref="Free"/> methods. /// </summary> [Conditional("DEBUG")] internal void VerifyTemps() { Debug.Assert(_usedTemps == null || _usedTemps.Count == 0); } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/AssemblyInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; [assembly: ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; [assembly: ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Methodical/fp/exgen/5w1d-04_cs_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize>False</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="5w1d-04.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize>False</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="5w1d-04.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/SIMD/Dup_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Dup.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Dup.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/bgt_r4.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="bgt_r4.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="bgt_r4.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/multiple-authors-source.xml
<!-- Description: a source with two atom:author elements produces no error 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> <source> <title>Source of all knowledge</title> <id>urn:uuid:28213c50-f84c-11d9-8cd6-0800200c9a66</id> <updated>2003-12-13T17:46:27Z</updated> <author> <name>Author Name</name> </author> <author> <name>input name</name> </author> </source> <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>Some text.</summary> </entry> </feed>
<!-- Description: a source with two atom:author elements produces no error 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> <source> <title>Source of all knowledge</title> <id>urn:uuid:28213c50-f84c-11d9-8cd6-0800200c9a66</id> <updated>2003-12-13T17:46:27Z</updated> <author> <name>Author Name</name> </author> <author> <name>input name</name> </author> </source> <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>Some text.</summary> </entry> </feed>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Regression/JitBlue/DevDiv_278372/DevDiv_278372.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This test is a reduced repro case for DevDiv VSO bug 278372. // The failure mode is that the RyuJIT/x86 backend was not correctly // handling the case of a variable involving a variable V such that: // - V is lvMustInit (therefore it must be undefined on some path) // - V lives in multiple registers, but never on the stack // - there is at least one other variable that is also lvMustInit, but that // has a stack location. // // In this case, genFnProlog was attempting to zero-init V on the stack. // // It was difficult to construct a repro; this repro requires that the test // be run with COMPlus_JitStressRegs=0x200 (which changes the location of // variables at block boundaries). // Metadata version: v4.0.30319 .assembly extern System.Runtime { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 4:1:0:0 } .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 4:0:0:0 } .assembly DevDiv_278372 { } .assembly extern xunit.core {} // =============== CLASS MEMBERS DECLARATION =================== .class private auto ansi beforefieldinit DevDiv_278372 extends [System.Runtime]System.Object { .method public hidebysig static bool check(int32& dummy) cil managed noinlining { ldc.i4.1 ret } // end of method DevDiv_278372::check .method public hidebysig static int32 getX() cil managed noinlining { ldc.i4.s 25 ret } // end of method DevDiv_278372::getX .method public hidebysig static int32 getY() cil managed noinlining { ldc.i4.5 ret } // end of method DevDiv_278372::getY .method public hidebysig static int32 Test(int32 x, int32 y, int32 x2, int32 y2, int32 x3, int32 y3) cil managed noinlining { .maxstack 2 .locals init ([0] int32 z, [1] int32 returnVal, [2] int32 dummy, [3] int32 z2) // Initialize returnVal to 100 ldc.i4.s 100 stloc.1 // Here we pass the address of "dummy" to ensure that we have a must-init on-stack variable. ldloca.s dummy call bool DevDiv_278372::check(int32&) brfalse.s L1 // Here we are conditionally defining "z", so that it will be must-init ldarg.0 ldarg.1 rem stloc.0 L1: ldloc.0 brfalse.s L2 ldc.i4.m1 stloc.1 L2: ldarg.2 ldarg.3 rem stloc.3 ldarg.0 ldarg.1 add stloc.0 ldloc.0 ldc.i4.s 30 beq.s L3 ldc.i4.m1 stloc.1 L3: ldloc.3 brfalse.s L4 ldc.i4.m1 stloc.1 L4: ldloc.1 ldc.i4.s 100 bne.un.s L5 ldstr "Pass" call void [System.Console]System.Console::WriteLine(string) br.s L6 L5: ldstr "Fail" call void [System.Console]System.Console::WriteLine(string) L6: ldloc.1 ret } // end of method DevDiv_278372::Test .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 16 (0x10) .maxstack 8 ldc.i4.s 25 ldc.i4.5 ldc.i4.s 25 ldc.i4.5 ldc.i4.s 25 ldc.i4.5 call int32 DevDiv_278372::Test(int32, int32, int32, int32, int32, int32) ret } // end of method DevDiv_278372::Main .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } // end of method DevDiv_278372::.ctor } // end of class DevDiv_278372 // =============================================================
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This test is a reduced repro case for DevDiv VSO bug 278372. // The failure mode is that the RyuJIT/x86 backend was not correctly // handling the case of a variable involving a variable V such that: // - V is lvMustInit (therefore it must be undefined on some path) // - V lives in multiple registers, but never on the stack // - there is at least one other variable that is also lvMustInit, but that // has a stack location. // // In this case, genFnProlog was attempting to zero-init V on the stack. // // It was difficult to construct a repro; this repro requires that the test // be run with COMPlus_JitStressRegs=0x200 (which changes the location of // variables at block boundaries). // Metadata version: v4.0.30319 .assembly extern System.Runtime { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 4:1:0:0 } .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 4:0:0:0 } .assembly DevDiv_278372 { } .assembly extern xunit.core {} // =============== CLASS MEMBERS DECLARATION =================== .class private auto ansi beforefieldinit DevDiv_278372 extends [System.Runtime]System.Object { .method public hidebysig static bool check(int32& dummy) cil managed noinlining { ldc.i4.1 ret } // end of method DevDiv_278372::check .method public hidebysig static int32 getX() cil managed noinlining { ldc.i4.s 25 ret } // end of method DevDiv_278372::getX .method public hidebysig static int32 getY() cil managed noinlining { ldc.i4.5 ret } // end of method DevDiv_278372::getY .method public hidebysig static int32 Test(int32 x, int32 y, int32 x2, int32 y2, int32 x3, int32 y3) cil managed noinlining { .maxstack 2 .locals init ([0] int32 z, [1] int32 returnVal, [2] int32 dummy, [3] int32 z2) // Initialize returnVal to 100 ldc.i4.s 100 stloc.1 // Here we pass the address of "dummy" to ensure that we have a must-init on-stack variable. ldloca.s dummy call bool DevDiv_278372::check(int32&) brfalse.s L1 // Here we are conditionally defining "z", so that it will be must-init ldarg.0 ldarg.1 rem stloc.0 L1: ldloc.0 brfalse.s L2 ldc.i4.m1 stloc.1 L2: ldarg.2 ldarg.3 rem stloc.3 ldarg.0 ldarg.1 add stloc.0 ldloc.0 ldc.i4.s 30 beq.s L3 ldc.i4.m1 stloc.1 L3: ldloc.3 brfalse.s L4 ldc.i4.m1 stloc.1 L4: ldloc.1 ldc.i4.s 100 bne.un.s L5 ldstr "Pass" call void [System.Console]System.Console::WriteLine(string) br.s L6 L5: ldstr "Fail" call void [System.Console]System.Console::WriteLine(string) L6: ldloc.1 ret } // end of method DevDiv_278372::Test .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 16 (0x10) .maxstack 8 ldc.i4.s 25 ldc.i4.5 ldc.i4.s 25 ldc.i4.5 ldc.i4.s 25 ldc.i4.5 call int32 DevDiv_278372::Test(int32, int32, int32, int32, int32, int32) ret } // end of method DevDiv_278372::Main .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } // end of method DevDiv_278372::.ctor } // end of class DevDiv_278372 // =============================================================
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/jit64/valuetypes/nullable/castclass/castclass/castclass032.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass032.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass032.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.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.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.WebAssembly.Diagnostics; using Newtonsoft.Json.Linq; using Xunit; namespace DebuggerTests { // TODO: static async, static method args public class EvaluateOnCallFrameTests : DebuggerTestBase { public static IEnumerable<object[]> InstanceMethodsTestData(string type_name) { yield return new object[] { type_name, "InstanceMethod", "InstanceMethod", false }; yield return new object[] { type_name, "GenericInstanceMethod", "GenericInstanceMethod<int>", false }; yield return new object[] { type_name, "InstanceMethodAsync", "MoveNext", true }; yield return new object[] { type_name, "GenericInstanceMethodAsync", "MoveNext", true }; // TODO: { "DebuggerTests.EvaluateTestsGeneric`1", "Instance", 9, "EvaluateTestsGenericStructInstanceMethod", prefix } } public static IEnumerable<object[]> InstanceMethodForTypeMembersTestData(string type_name) { foreach (var data in InstanceMethodsTestData(type_name)) { yield return new object[] { "", 0 }.Concat(data).ToArray(); yield return new object[] { "this.", 0 }.Concat(data).ToArray(); yield return new object[] { "NewInstance.", 3 }.Concat(data).ToArray(); yield return new object[] { "this.NewInstance.", 3 }.Concat(data).ToArray(); } } public static IEnumerable<object[]> EvaluateStaticClassFromStaticMethodTestData(string type_name) { yield return new object[] { type_name, "EvaluateAsyncMethods", "EvaluateAsyncMethods", true }; yield return new object[] { type_name, "EvaluateMethods", "EvaluateMethods", false }; } [Theory] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateTypeInstanceMembers(string prefix, int bias, string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/1, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dateTime = new DateTime(2010, 9, 8, 7, 6, 5 + bias); var DTProp = dateTime.AddMinutes(10); foreach (var pad in new[] { String.Empty, " " }) { var padded_prefix = pad + prefix; await EvaluateOnCallFrameAndCheck(id, ($"{padded_prefix}a", TNumber(4)), // fields ($"{padded_prefix}dateTime.TimeOfDay", TValueType("System.TimeSpan", dateTime.TimeOfDay.ToString())), ($"{padded_prefix}dateTime", TDateTime(dateTime)), ($"{padded_prefix}dateTime.TimeOfDay.Minutes", TNumber(dateTime.TimeOfDay.Minutes)), // properties ($"{padded_prefix}DTProp.TimeOfDay.Minutes", TNumber(DTProp.TimeOfDay.Minutes)), ($"{padded_prefix}DTProp", TDateTime(DTProp)), ($"{padded_prefix}DTProp.TimeOfDay", TValueType("System.TimeSpan", DTProp.TimeOfDay.ToString())), ($"{padded_prefix}IntProp", TNumber(9)), ($"{padded_prefix}NullIfAIsNotZero", TObject("DebuggerTests.EvaluateTestsClassWithProperties", is_null: true)) ); } }); [Theory] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateInstanceMethodArguments(string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/1, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var DTProp = new DateTime(2010, 9, 8, 7, 6, 5).AddMinutes(10); await EvaluateOnCallFrameAndCheck(id, ("g", TNumber(400)), ("h", TNumber(123)), ("valString", TString("just a test")), ("me", TObject(type)), // property on method arg ("me.DTProp", TDateTime(DTProp)), ("me.DTProp.TimeOfDay.Minutes", TNumber(DTProp.TimeOfDay.Minutes)), ("me.DTProp.Second + (me.IntProp - 5)", TNumber(DTProp.Second + 4))); }); [Theory] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateMethodLocals(string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/5, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dt = new DateTime(2025, 3, 5, 7, 9, 11); await EvaluateOnCallFrameAndCheck(id, (" d ", TNumber(401)), ("d", TNumber(401)), (" d", TNumber(401)), ("e", TNumber(402)), ("f", TNumber(403)), // property on a local ("local_dt", TDateTime(dt)), (" local_dt", TDateTime(dt)), ("local_dt.Date", TDateTime(dt.Date)), (" local_dt.Date", TDateTime(dt.Date))); }); [Fact] public async Task EvaluateStaticLocalsWithDeepMemberAccess() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dt = new DateTime(2020, 1, 2, 3, 4, 5); await EvaluateOnCallFrameAndCheck(id, ("f_s.c", TNumber(4)), ("f_s", TValueType("DebuggerTests.EvaluateTestsStructWithProperties")), ("f_s.dateTime", TDateTime(dt)), ("f_s.dateTime.Date", TDateTime(dt.Date))); }); [Fact] public async Task EvaluateLocalsAsync() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.Point", "AsyncInstanceMethod", 1, "MoveNext", "window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.ArrayTestsClass:EntryPointForStructMethod', true); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); // sc_arg { var (sc_arg, _) = await EvaluateOnCallFrame(id, "sc_arg"); await CheckValue(sc_arg, TObject("DebuggerTests.SimpleClass"), nameof(sc_arg)); // Check that we did get the correct object var sc_arg_props = await GetProperties(sc_arg["objectId"]?.Value<string>()); await CheckProps(sc_arg_props, new { X = TNumber(10), Y = TNumber(45), Id = TString("sc#Id"), Color = TEnum("DebuggerTests.RGB", "Blue"), PointWithCustomGetter = TGetter("PointWithCustomGetter") }, "sc_arg_props#1"); await EvaluateOnCallFrameAndCheck(id, ("(sc_arg.PointWithCustomGetter.X)", TNumber(100)), ("sc_arg.Id + \"_foo\"", TString($"sc#Id_foo")), ("sc_arg.Id + (sc_arg.X==10 ? \"_is_ten\" : \"_not_ten\")", TString($"sc#Id_is_ten"))); } // local_gs { var (local_gs, _) = await EvaluateOnCallFrame(id, "local_gs"); await CheckValue(local_gs, TValueType("DebuggerTests.SimpleGenericStruct<int>"), nameof(local_gs)); (local_gs, _) = await EvaluateOnCallFrame(id, " local_gs"); await CheckValue(local_gs, TValueType("DebuggerTests.SimpleGenericStruct<int>"), nameof(local_gs)); var local_gs_props = await GetProperties(local_gs["objectId"]?.Value<string>()); await CheckProps(local_gs_props, new { Id = TObject("string", is_null: true), Color = TEnum("DebuggerTests.RGB", "Red"), Value = TNumber(0) }, "local_gs_props#1"); await EvaluateOnCallFrameAndCheck(id, ("(local_gs.Id)", TString(null))); } }); [Theory] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateExpressionsWithDeepMemberAccesses(string prefix, int bias, string type, string method, string bp_function_name, bool _) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/4, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dateTime = new DateTime(2010, 9, 8, 7, 6, 5 + bias); var DTProp = dateTime.AddMinutes(10); await EvaluateOnCallFrameAndCheck(id, ($"{prefix}a + 5", TNumber(9)), ($"10 + {prefix}IntProp", TNumber(19)), ($" {prefix}IntProp + {prefix}DTProp.Second", TNumber(9 + DTProp.Second)), ($" {prefix}IntProp + ({prefix}DTProp.Second+{prefix}dateTime.Year)", TNumber(9 + DTProp.Second + dateTime.Year)), ($" {prefix}DTProp.Second > 0 ? \"_foo_\": \"_zero_\"", TString("_foo_")), // local_dt is not live yet ($"local_dt.Date.Year * 10", TNumber(10))); }); [Theory] [InlineData("")] [InlineData("this.")] public async Task InheritedAndPrivateMembersInAClass(string prefix) => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.GetPropertiesTests.DerivedClass", "InstanceMethod", 1, "InstanceMethod", $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] DebuggerTests.GetPropertiesTests.DerivedClass:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); foreach (var pad in new[] { String.Empty, " " }) { var padded_prefix = pad + prefix; await EvaluateOnCallFrameAndCheck(id, // overridden ($"{padded_prefix}FirstName + \"_foo\"", TString("DerivedClass#FirstName_foo")), ($"{padded_prefix}DateTimeForOverride.Date.Year", TNumber(2190)), ($"{padded_prefix}DateTimeForOverride.Date.Year - 10", TNumber(2180)), ($"\"foo_\" + {padded_prefix}StringPropertyForOverrideWithAutoProperty", TString("foo_DerivedClass#StringPropertyForOverrideWithAutoProperty")), // private ($"{padded_prefix}_stringField + \"_foo\"", TString("DerivedClass#_stringField_foo")), ($"{padded_prefix}_stringField", TString("DerivedClass#_stringField")), ($"{padded_prefix}_dateTime.Second + 4", TNumber(7)), ($"{padded_prefix}_DTProp.Second + 4", TNumber(13)), // inherited public ($"\"foo_\" + {padded_prefix}Base_AutoStringProperty", TString("foo_base#Base_AutoStringProperty")), // inherited private ($"{padded_prefix}_base_dateTime.Date.Year - 10", TNumber(2124)) ); } }); [Fact] public async Task EvaluateSimpleExpressions() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, // "((this))", TObject("foo")); //FIXME: // "((dt))", TObject("foo")); //FIXME: ("this", TObject("DebuggerTests.EvaluateTestsClass.TestEvaluate")), (" this", TObject("DebuggerTests.EvaluateTestsClass.TestEvaluate")), ("5", TNumber(5)), (" 5", TNumber(5)), ("d + e", TNumber(203)), ("e + 10", TNumber(112)), // repeated expressions ("this.a + this.a", TNumber(2)), ("a + \"_\" + a", TString("9000_9000")), ("a+(a )", TString("90009000")), // possible duplicate arg name ("this.a + this_a", TNumber(46)), ("this.a + this.b", TNumber(3)), ("\"test\" + \"test\"", TString("testtest")), ("5 + 5", TNumber(10))); }); public static TheoryData<string, string, string> ShadowMethodArgsTestData => new TheoryData<string, string, string> { { "DebuggerTests.EvaluateTestsClassWithProperties", "EvaluateShadow", "EvaluateShadow" }, { "DebuggerTests.EvaluateTestsClassWithProperties", "EvaluateShadowAsync", "MoveNext" }, { "DebuggerTests.EvaluateTestsStructWithProperties", "EvaluateShadow", "EvaluateShadow" }, { "DebuggerTests.EvaluateTestsStructWithProperties", "EvaluateShadowAsync", "MoveNext" }, }; [Theory] [MemberData(nameof(ShadowMethodArgsTestData))] public async Task LocalsAndArgsShadowingThisMembers(string type_name, string method, string bp_function_name) => await CheckInspectLocalsAtBreakpointSite( type_name, method, 2, bp_function_name, "window.setTimeout(function() { invoke_static_method ('[debugger-test] " + type_name + ":run'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("a", TString("hello")), ("this.a", TNumber(4))); await CheckExpressions("this.", new DateTime(2010, 9, 8, 7, 6, 5 + 0)); await CheckExpressions(String.Empty, new DateTime(2020, 3, 4, 5, 6, 7)); async Task CheckExpressions(string prefix, DateTime dateTime) { await EvaluateOnCallFrameAndCheck(id, (prefix + "dateTime", TDateTime(dateTime)), (prefix + "dateTime.TimeOfDay.Minutes", TNumber(dateTime.TimeOfDay.Minutes)), (prefix + "dateTime.TimeOfDay", TValueType("System.TimeSpan", dateTime.TimeOfDay.ToString()))); } }); [Theory] [InlineData("DebuggerTests.EvaluateTestsStructWithProperties", true)] [InlineData("DebuggerTests.EvaluateTestsClassWithProperties", false)] public async Task EvaluateOnPreviousFrames(string type_name, bool is_valuetype) => await CheckInspectLocalsAtBreakpointSite( type_name, "EvaluateShadow", 1, "EvaluateShadow", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] {type_name}:run'); }})", wait_for_event_fn: async (pause_location) => { var dt_local = new DateTime(2020, 3, 4, 5, 6, 7); var dt_this = new DateTime(2010, 9, 8, 7, 6, 5); // At EvaluateShadow { var id0 = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id0, ("dateTime", TDateTime(dt_local)), ("this.dateTime", TDateTime(dt_this)) ); await EvaluateOnCallFrameFail(id0, ("obj.IntProp", "ReferenceError")); } { var id1 = pause_location["callFrames"][1]["callFrameId"].Value<string>(); await EvaluateOnCallFrameFail(id1, ("dateTime", "ReferenceError"), ("this.dateTime", "ReferenceError")); // obj available only on the -1 frame await EvaluateOnCallFrameAndCheck(id1, ("obj.IntProp", TNumber(7))); } await SetBreakpointInMethod("debugger-test.dll", type_name, "SomeMethod", 1); pause_location = await SendCommandAndCheck(null, "Debugger.resume", null, 0, 0, "SomeMethod"); // At SomeMethod // TODO: change types also.. so, that `this` is different! // Check frame0 { var id0 = pause_location["callFrames"][0]["callFrameId"].Value<string>(); // 'me' and 'dateTime' are reversed in this method await EvaluateOnCallFrameAndCheck(id0, ("dateTime", is_valuetype ? TValueType(type_name) : TObject(type_name)), ("this.dateTime", TDateTime(dt_this)), ("me", TDateTime(dt_local)), // local variable shadows field, but isn't "live" yet ("DTProp", TString(null)), // access field via `this.` ("this.DTProp", TDateTime(dt_this.AddMinutes(10)))); await EvaluateOnCallFrameFail(id0, ("obj", "ReferenceError")); } // check frame1 { var id1 = pause_location["callFrames"][1]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id1, // 'me' and 'dateTime' are reversed in this method ("dateTime", TDateTime(dt_local)), ("this.dateTime", TDateTime(dt_this)), ("me", is_valuetype ? TValueType(type_name) : TObject(type_name)), // not shadowed here ("DTProp", TDateTime(dt_this.AddMinutes(10))), // access field via `this.` ("this.DTProp", TDateTime(dt_this.AddMinutes(10)))); await EvaluateOnCallFrameFail(id1, ("obj", "ReferenceError")); } // check frame2 { var id2 = pause_location["callFrames"][2]["callFrameId"].Value<string>(); // Only obj should be available await EvaluateOnCallFrameFail(id2, ("dateTime", "ReferenceError"), ("this.dateTime", "ReferenceError"), ("me", "ReferenceError")); await EvaluateOnCallFrameAndCheck(id2, ("obj", is_valuetype ? TValueType(type_name) : TObject(type_name))); } }); [Fact] public async Task JSEvaluate() { var bp_loc = "/other.js"; var line = 78; var col = 1; await SetBreakpoint(bp_loc, line, col); var eval_expr = "window.setTimeout(function() { eval_call_on_frame_test (); }, 1)"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameFail(id, ("me.foo", null), ("obj.foo.bar", null)); await EvaluateOnCallFrame(id, "obj.foo", expect_ok: true); } [Fact] public async Task NegativeTestsInInstanceMethod() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); // Use '.' on a primitive member await EvaluateOnCallFrameFail(id, //BUG: TODO: //("a)", "CompilationError"), ("this.a.", "ReferenceError"), ("a.", "ReferenceError"), ("this..a", "CompilationError"), (".a.", "ReferenceError"), ("me.foo", "ReferenceError"), ("this.a + non_existant", "ReferenceError"), ("this.NullIfAIsNotZero.foo", "ReferenceError"), ("NullIfAIsNotZero.foo", "ReferenceError")); }); [Fact] public async Task NegativeTestsInStaticMethod() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameFail(id, ("me.foo", "ReferenceError"), ("this", "CompilationError"), ("this.NullIfAIsNotZero.foo", "ReferenceError")); }); [Fact] public async Task EvaluatePropertyThatThrows() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClassWithProperties", "InstanceMethod", /*line_offset*/1, "InstanceMethod", $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] DebuggerTests.EvaluateTestsClassWithProperties:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.PropertyThrowException", TString("System.Exception: error"))); }); async Task EvaluateOnCallFrameFail(string call_frame_id, params (string expression, string class_name)[] args) { foreach (var arg in args) { var (_, res) = await EvaluateOnCallFrame(call_frame_id, arg.expression, expect_ok: false); if (arg.class_name != null) AssertEqual(arg.class_name, res.Error["result"]?["className"]?.Value<string>(), $"Error className did not match for expression '{arg.expression}'"); } } [Fact] [Trait("Category", "windows-failing")] // https://github.com/dotnet/runtime/issues/65744 [Trait("Category", "linux-failing")] // https://github.com/dotnet/runtime/issues/65744 public async Task EvaluateSimpleMethodCallsError() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (_, res) = await EvaluateOnCallFrame(id, "this.objToTest.MyMethodWrong()", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethodWrong'", res.Error["message"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.objToTest.MyMethod(1)", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethod'. Too many arguments passed.", res.Error["result"]["description"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.CallMethodWithParm(\"1\")", expect_ok: false ); AssertEqual("Unable to evaluate method 'CallMethodWithParm'", res.Error["message"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.ParmToTestObjNull.MyMethod()", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethod'", res.Error["message"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.ParmToTestObjException.MyMethod()", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethod'", res.Error["message"]?.Value<string>(), "wrong error message"); }); [Fact] public async Task EvaluateSimpleMethodCallsWithoutParms() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethod()", TNumber(1)), ("this.CallMethod()", TNumber(1)), ("this.CallMethodReturningChar()", TChar('A')), ("this.ParmToTestObj.MyMethod()", TString("methodOK")), ("this.ParmToTestObj.ToString()", TString("DebuggerTests.EvaluateMethodTestsClass+ParmToTest")), ("this.objToTest.MyMethod()", TString("methodOK"))); }); [Fact] public async Task EvaluateSimpleMethodCallsWithConstParms() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethodWithParm(10)", TNumber(11)), ("this.CallMethodWithMultipleParms(10, 10)", TNumber(21)), ("this.CallMethodWithParmBool(true)", TString("TRUE")), ("this.CallMethodWithParmBool(false)", TString("FALSE")), ("this.CallMethodWithParmString(\"concat\")", TString("str_const_concat")), ("this.CallMethodWithParmString(\"\\\"\\\"\")", TString("str_const_\"\"")), ("this.CallMethodWithParmString(\"🛶\")", TString("str_const_🛶")), ("this.CallMethodWithParmString(\"\\uD83D\\uDEF6\")", TString("str_const_🛶")), ("this.CallMethodWithParmString(\"🚀\")", TString("str_const_🚀")), ("this.CallMethodWithParmString_λ(\"🚀\")", TString("λ_🚀")), ("this.CallMethodWithParm(10) + this.a", TNumber(12)), ("this.CallMethodWithObj(null)", TNumber(-1)), ("this.CallMethodWithChar('a')", TString("str_const_a"))); }); [Fact] public async Task EvaluateSimpleMethodCallsWithVariableParms() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethodWithParm(this.a)", TNumber(2)), ("this.CallMethodWithMultipleParms(this.a, 10)", TNumber(12)), ("this.CallMethodWithParmString(this.str)", TString("str_const_str_const_")), ("this.CallMethodWithParmBool(this.t)", TString("TRUE")), ("this.CallMethodWithParmBool(this.f)", TString("FALSE")), ("this.CallMethodWithParm(this.a) + this.a", TNumber(3)), ("this.CallMethodWithObj(this.objToTest)", TNumber(10))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessByConstant() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.numList[0]", TNumber(1)), ("f.textList[1]", TString("2")), ("f.numArray[1]", TNumber(2)), ("f.textArray[0]", TString("1"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessByLocalVariable() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.numList[i]", TNumber(1)), ("f.textList[j]", TString("2")), ("f.numArray[j]", TNumber(2)), ("f.textArray[i]", TString("1"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessByMemberVariables() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.idx0", TNumber(0)), ("f.idx1", TNumber(1)), ("f.numList[f.idx0]", TNumber(1)), ("f.textList[f.idx1]", TString("2")), ("f.numArray[f.idx1]", TNumber(2)), ("f.textArray[f.idx0]", TString("1"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessNested() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.idx0", TNumber(0)), ("f.numList[f.numList[f.idx0]]", TNumber(2)), ("f.textList[f.numList[f.idx0]]", TString("2")), ("f.numArray[f.numArray[f.idx0]]", TNumber(2)), ("f.textArray[f.numArray[f.idx0]]", TString("2"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessMultidimentional() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("j", TNumber(1)), ("f.idx1", TNumber(1)), ("f.numArrayOfArrays[1][1]", TNumber(2)), ("f.numArrayOfArrays[j][j]", TNumber(2)), ("f.numArrayOfArrays[f.idx1][f.idx1]", TNumber(2)), ("f.numListOfLists[1][1]", TNumber(2)), ("f.numListOfLists[j][j]", TNumber(2)), ("f.numListOfLists[f.idx1][f.idx1]", TNumber(2)), ("f.textArrayOfArrays[1][1]", TString("2")), ("f.textArrayOfArrays[j][j]", TString("2")), ("f.textArrayOfArrays[f.idx1][f.idx1]", TString("2")), ("f.textListOfLists[1][1]", TString("2")), ("f.textListOfLists[j][j]", TString("2")), ("f.textListOfLists[f.idx1][f.idx1]", TString("2"))); }); [Fact] public async Task EvaluateSimpleMethodCallsCheckChangedValue() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; var props = await GetObjectOnFrame(frame, "this"); CheckNumber(props, "a", 1); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethodChangeValue()", TObject("object", is_null : true))); frame = pause_location["callFrames"][0]; props = await GetObjectOnFrame(frame, "this"); CheckNumber(props, "a", 11); }); [Fact] public async Task EvaluateStaticClass() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.StaticField1", TNumber(10))); await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.StaticProperty1", TString("StaticProperty1"))); await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Theory] [MemberData(nameof(EvaluateStaticClassFromStaticMethodTestData), parameters: "DebuggerTests.EvaluateMethodTestsClass")] // [MemberData(nameof(EvaluateStaticClassFromStaticMethodTestData), parameters: "EvaluateMethodTestsClass")] public async Task EvaluateStaticClassFromStaticMethod(string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, 1, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] {type}:{method}'); }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("EvaluateStaticClass.StaticField1", TNumber(10)), ("EvaluateStaticClass.StaticProperty1", TString("StaticProperty1")), ("EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented")), ("DebuggerTests.EvaluateStaticClass.StaticField1", TNumber(10)), ("DebuggerTests.EvaluateStaticClass.StaticProperty1", TString("StaticProperty1")), ("DebuggerTests.EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Fact] public async Task EvaluateNonStaticClassWithStaticFields() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass", "EvaluateAsyncMethods", 3, "EvaluateAsyncMethods", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateAsyncMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateNonStaticClassWithStaticFields.StaticField1", TNumber(10)), ("DebuggerTests.EvaluateNonStaticClassWithStaticFields.StaticProperty1", TString("StaticProperty1")), ("DebuggerTests.EvaluateNonStaticClassWithStaticFields.StaticPropertyWithError", TString("System.Exception: not implemented")), ("EvaluateNonStaticClassWithStaticFields.StaticField1", TNumber(10)), ("EvaluateNonStaticClassWithStaticFields.StaticProperty1", TString("StaticProperty1")), ("EvaluateNonStaticClassWithStaticFields.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Fact] public async Task EvaluateStaticClassesNested() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass", "EvaluateMethods", 3, "EvaluateMethods", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticField1", TNumber(3)), ("DebuggerTests.EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticProperty1", TString("StaticProperty3")), ("DebuggerTests.EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticPropertyWithError", TString("System.Exception: not implemented 3")), ("EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticField1", TNumber(3)), ("EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticProperty1", TString("StaticProperty3")), ("EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticPropertyWithError", TString("System.Exception: not implemented 3"))); }); [Fact] public async Task EvaluateStaticClassesNestedWithNoNamespace() => await CheckInspectLocalsAtBreakpointSite( "NoNamespaceClass", "EvaluateMethods", 1, "EvaluateMethods", "window.setTimeout(function() { invoke_static_method ('[debugger-test] NoNamespaceClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("NoNamespaceClass.NestedClass1.NestedClass2.NestedClass3.StaticField1", TNumber(30)), ("NoNamespaceClass.NestedClass1.NestedClass2.NestedClass3.StaticProperty1", TString("StaticProperty30")), ("NoNamespaceClass.NestedClass1.NestedClass2.NestedClass3.StaticPropertyWithError", TString("System.Exception: not implemented 30"))); }); [Fact] public async Task EvaluateStaticClassesFromDifferentNamespaceInDifferentFrames() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTestsV2.EvaluateStaticClass", "Run", 1, "Run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id_top = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id_top, ("EvaluateStaticClass.StaticField1", TNumber(20)), ("EvaluateStaticClass.StaticProperty1", TString("StaticProperty2")), ("EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); var id_second = pause_location["callFrames"][1]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id_second, ("EvaluateStaticClass.StaticField1", TNumber(10)), ("EvaluateStaticClass.StaticProperty1", TString("StaticProperty1")), ("EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Fact] public async Task EvaluateStaticClassInvalidField() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; var (_, res) = await EvaluateOnCallFrame(id, "DebuggerTests.EvaluateStaticClass.StaticProperty2", expect_ok: false); AssertEqual("Failed to resolve member access for DebuggerTests.EvaluateStaticClass.StaticProperty2", res.Error["result"]?["description"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "DebuggerTests.InvalidEvaluateStaticClass.StaticProperty2", expect_ok: false); AssertEqual("Failed to resolve member access for DebuggerTests.InvalidEvaluateStaticClass.StaticProperty2", res.Error["result"]?["description"]?.Value<string>(), "wrong error message"); }); [Fact] public async Task AsyncLocalsInContinueWithBlock() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.AsyncTests.ContinueWithTests", "ContinueWithStaticAsync", 4, "<ContinueWithStaticAsync>b__3_0", "window.setTimeout(function() { invoke_static_method('[debugger-test] DebuggerTests.AsyncTests.ContinueWithTests:RunAsync'); })", wait_for_event_fn: async (pause_location) => { var frame_locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value<string>()); var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ($"t.Status", TEnum("System.Threading.Tasks.TaskStatus", "RanToCompletion")), ($" t.Status", TEnum("System.Threading.Tasks.TaskStatus", "RanToCompletion")) ); await EvaluateOnCallFrameFail(id, ("str", "ReferenceError"), (" str", "ReferenceError") ); }); [Fact] public async Task EvaluateConstantValueUsingRuntimeEvaluate() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var dt = new DateTime(2020, 1, 2, 3, 4, 5); await RuntimeEvaluateAndCheck( ("15\n//comment as vs does\n", TNumber(15)), ("15", TNumber(15)), ("\"15\"\n//comment as vs does\n", TString("15")), ("\"15\"", TString("15"))); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsNone", "testFieldsNone", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesNone", "testPropertiesNone", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesNone", "testPropertiesNone", 5, true)] public async Task EvaluateBrowsableNone(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testNone, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testNone, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testNone)); var testNoneProps = await GetProperties(testNone["objectId"]?.Value<string>()); if (isCustomGetter) await CheckProps(testNoneProps, new { list = TGetter("list", TObject("System.Collections.Generic.List<int>", description: "Count = 2")), array = TGetter("array", TObject("int[]", description: "int[2]")), text = TGetter("text", TString("text")) }, "testNoneProps#1"); else await CheckProps(testNoneProps, new { list = TObject("System.Collections.Generic.List<int>", description: "Count = 2"), array = TObject("int[]", description: "int[2]"), text = TString("text") }, "testNoneProps#1"); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsNever", "testFieldsNever", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsNever", "testFieldsNever", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 5)] public async Task EvaluateBrowsableNever(string outerClassName, string className, string localVarName, int breakLine) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testNever, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testNever, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testNever)); var testNeverProps = await GetProperties(testNever["objectId"]?.Value<string>()); await CheckProps(testNeverProps, new { }, "testNeverProps#1"); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsCollapsed", "testFieldsCollapsed", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsCollapsed", "testFieldsCollapsed", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 5, true)] public async Task EvaluateBrowsableCollapsed(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testCollapsed, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testCollapsed, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testCollapsed)); var testCollapsedProps = await GetProperties(testCollapsed["objectId"]?.Value<string>()); if (isCustomGetter) await CheckProps(testCollapsedProps, new { listCollapsed = TGetter("listCollapsed", TObject("System.Collections.Generic.List<int>", description: "Count = 2")), arrayCollapsed = TGetter("arrayCollapsed", TObject("int[]", description: "int[2]")), textCollapsed = TGetter("textCollapsed", TString("textCollapsed")) }, "testCollapsedProps#1"); else await CheckProps(testCollapsedProps, new { listCollapsed = TObject("System.Collections.Generic.List<int>", description: "Count = 2"), arrayCollapsed = TObject("int[]", description: "int[2]"), textCollapsed = TString("textCollapsed") }, "testCollapsedProps#1"); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsRootHidden", "testFieldsRootHidden", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsRootHidden", "testFieldsRootHidden", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 5, true)] public async Task EvaluateBrowsableRootHidden(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testRootHidden, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testRootHidden, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testRootHidden)); var testRootHiddenProps = await GetProperties(testRootHidden["objectId"]?.Value<string>()); var (refList, _) = await EvaluateOnCallFrame(id, "testPropertiesNone.list"); var refListProp = await GetProperties(refList["objectId"]?.Value<string>()); var refListElementsProp = await GetProperties(refListProp[0]["value"]["objectId"]?.Value<string>()); var (refArray, _) = await EvaluateOnCallFrame(id, "testPropertiesNone.array"); var refArrayProp = await GetProperties(refArray["objectId"]?.Value<string>()); //in Console App names are in [] //adding variable name to make elements unique foreach (var item in refArrayProp) { item["name"] = string.Concat("arrayRootHidden[", item["name"], "]"); } foreach (var item in refListElementsProp) { item["name"] = string.Concat("listRootHidden[", item["name"], "]"); } var mergedRefItems = new JArray(refListElementsProp.Union(refArrayProp)); Assert.Equal(mergedRefItems, testRootHiddenProps); }); [Fact] public async Task EvaluateStaticAttributeInAssemblyNotRelatedButLoaded() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { await RuntimeEvaluateAndCheck( ("ClassToBreak.valueToCheck", TNumber(10))); }); [Fact] public async Task EvaluateLocalObjectFromAssemblyNotRelatedButLoaded() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocalsFromAnotherAssembly", 5, "EvaluateLocalsFromAnotherAssembly", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocalsFromAnotherAssembly'); })", wait_for_event_fn: async (pause_location) => { await RuntimeEvaluateAndCheck( ("a.valueToCheck", TNumber(20))); }); [Fact] public async Task EvaluateProtectionLevels() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateProtectionLevels", "Evaluate", 2, "Evaluate", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateProtectionLevels:Evaluate'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (obj, _) = await EvaluateOnCallFrame(id, "testClass"); var (pub, internalAndProtected, priv) = await GetPropertiesSortedByProtectionLevels(obj["objectId"]?.Value<string>()); Assert.True(pub[0] != null); Assert.True(internalAndProtected[0] != null); Assert.True(internalAndProtected[1] != null); Assert.True(priv[0] != null); Assert.Equal(pub[0]["value"]["value"], "public"); Assert.Equal(internalAndProtected[0]["value"]["value"], "internal"); Assert.Equal(internalAndProtected[1]["value"]["value"], "protected"); Assert.Equal(priv[0]["value"]["value"], "private"); }); [Fact] public async Task StructureGetters() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.StructureGetters", "Evaluate", 2, "Evaluate", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.StructureGetters:Evaluate'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (obj, _) = await EvaluateOnCallFrame(id, "s"); var props = await GetProperties(obj["objectId"]?.Value<string>()); await CheckProps(props, new { Id = TGetter("Id", TNumber(123)) }, "s#1"); var getter = props.FirstOrDefault(p => p["name"]?.Value<string>() == "Id"); Assert.NotNull(getter); var getterId = getter["get"]["objectId"]?.Value<string>(); var getterProps = await GetProperties(getterId); Assert.Equal(getterProps[0]?["value"]?["value"]?.Value<int>(), 123); }); [Fact] public async Task EvaluateMethodWithDefaultParam() => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.DefaultParamMethods", "Evaluate", 2, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.DefaultParamMethods:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("test.GetByte()", TNumber(1)), ("test.GetSByte()", TNumber(1)), ("test.GetByteNullable()", TNumber(1)), ("test.GetSByteNullable()", TNumber(1)), ("test.GetInt16()", TNumber(1)), ("test.GetUInt16()", TNumber(1)), ("test.GetInt16Nullable()", TNumber(1)), ("test.GetUInt16Nullable()", TNumber(1)), ("test.GetInt32()", TNumber(1)), ("test.GetUInt32()", TNumber(1)), ("test.GetInt32Nullable()", TNumber(1)), ("test.GetUInt32Nullable()", TNumber(1)), ("test.GetInt64()", TNumber(1)), ("test.GetUInt64()", TNumber(1)), ("test.GetInt64Nullable()", TNumber(1)), ("test.GetUInt64Nullable()", TNumber(1)), ("test.GetChar()", TChar('T')), ("test.GetCharNullable()", TChar('T')), ("test.GetUnicodeChar()", TChar('ą')), ("test.GetString()", TString("1.23")), ("test.GetUnicodeString()", TString("żółć")), ("test.GetString(null)", TObject("string", is_null: true)), ("test.GetStringNullable()", TString("1.23")), ("test.GetSingle()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetDouble()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetSingleNullable()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetDoubleNullable()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetBool()", JObject.FromObject( new { type = "object", value = true, description = "True", className = "System.Boolean" })), ("test.GetBoolNullable()", JObject.FromObject( new { type = "object", value = true, description = "True", className = "System.Boolean" })), ("test.GetNull()", JObject.FromObject( new { type = "object", value = true, description = "True", className = "System.Boolean" })), ("test.GetDefaultAndRequiredParam(2)", TNumber(5)), ("test.GetDefaultAndRequiredParam(3, 2)", TNumber(5)), ("test.GetDefaultAndRequiredParamMixedTypes(\"a\")", TString("a; -1; False")), ("test.GetDefaultAndRequiredParamMixedTypes(\"a\", 23)", TString("a; 23; False")), ("test.GetDefaultAndRequiredParamMixedTypes(\"a\", 23, true)", TString("a; 23; True")) ); var (_, res) = await EvaluateOnCallFrame(id, "test.GetDefaultAndRequiredParamMixedTypes(\"a\", 23, true, 1.23f)", expect_ok: false ); AssertEqual("Unable to evaluate method 'GetDefaultAndRequiredParamMixedTypes'. Too many arguments passed.", res.Error["result"]["description"]?.Value<string>(), "wrong error message"); }); [Fact] public async Task EvaluateMethodWithLinq() => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.DefaultParamMethods", "Evaluate", 2, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.DefaultParamMethods:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("test.listToLinq.ToList()", TObject("System.Collections.Generic.List<int>", description: "Count = 11")) ); }); } }
// 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.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.WebAssembly.Diagnostics; using Newtonsoft.Json.Linq; using Xunit; namespace DebuggerTests { // TODO: static async, static method args public class EvaluateOnCallFrameTests : DebuggerTestBase { public static IEnumerable<object[]> InstanceMethodsTestData(string type_name) { yield return new object[] { type_name, "InstanceMethod", "InstanceMethod", false }; yield return new object[] { type_name, "GenericInstanceMethod", "GenericInstanceMethod<int>", false }; yield return new object[] { type_name, "InstanceMethodAsync", "MoveNext", true }; yield return new object[] { type_name, "GenericInstanceMethodAsync", "MoveNext", true }; // TODO: { "DebuggerTests.EvaluateTestsGeneric`1", "Instance", 9, "EvaluateTestsGenericStructInstanceMethod", prefix } } public static IEnumerable<object[]> InstanceMethodForTypeMembersTestData(string type_name) { foreach (var data in InstanceMethodsTestData(type_name)) { yield return new object[] { "", 0 }.Concat(data).ToArray(); yield return new object[] { "this.", 0 }.Concat(data).ToArray(); yield return new object[] { "NewInstance.", 3 }.Concat(data).ToArray(); yield return new object[] { "this.NewInstance.", 3 }.Concat(data).ToArray(); } } public static IEnumerable<object[]> EvaluateStaticClassFromStaticMethodTestData(string type_name) { yield return new object[] { type_name, "EvaluateAsyncMethods", "EvaluateAsyncMethods", true }; yield return new object[] { type_name, "EvaluateMethods", "EvaluateMethods", false }; } [Theory] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateTypeInstanceMembers(string prefix, int bias, string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/1, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dateTime = new DateTime(2010, 9, 8, 7, 6, 5 + bias); var DTProp = dateTime.AddMinutes(10); foreach (var pad in new[] { String.Empty, " " }) { var padded_prefix = pad + prefix; await EvaluateOnCallFrameAndCheck(id, ($"{padded_prefix}a", TNumber(4)), // fields ($"{padded_prefix}dateTime.TimeOfDay", TValueType("System.TimeSpan", dateTime.TimeOfDay.ToString())), ($"{padded_prefix}dateTime", TDateTime(dateTime)), ($"{padded_prefix}dateTime.TimeOfDay.Minutes", TNumber(dateTime.TimeOfDay.Minutes)), // properties ($"{padded_prefix}DTProp.TimeOfDay.Minutes", TNumber(DTProp.TimeOfDay.Minutes)), ($"{padded_prefix}DTProp", TDateTime(DTProp)), ($"{padded_prefix}DTProp.TimeOfDay", TValueType("System.TimeSpan", DTProp.TimeOfDay.ToString())), ($"{padded_prefix}IntProp", TNumber(9)), ($"{padded_prefix}NullIfAIsNotZero", TObject("DebuggerTests.EvaluateTestsClassWithProperties", is_null: true)) ); } }); [Theory] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateInstanceMethodArguments(string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/1, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var DTProp = new DateTime(2010, 9, 8, 7, 6, 5).AddMinutes(10); await EvaluateOnCallFrameAndCheck(id, ("g", TNumber(400)), ("h", TNumber(123)), ("valString", TString("just a test")), ("me", TObject(type)), // property on method arg ("me.DTProp", TDateTime(DTProp)), ("me.DTProp.TimeOfDay.Minutes", TNumber(DTProp.TimeOfDay.Minutes)), ("me.DTProp.Second + (me.IntProp - 5)", TNumber(DTProp.Second + 4))); }); [Theory] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodsTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateMethodLocals(string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/5, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dt = new DateTime(2025, 3, 5, 7, 9, 11); await EvaluateOnCallFrameAndCheck(id, (" d ", TNumber(401)), ("d", TNumber(401)), (" d", TNumber(401)), ("e", TNumber(402)), ("f", TNumber(403)), // property on a local ("local_dt", TDateTime(dt)), (" local_dt", TDateTime(dt)), ("local_dt.Date", TDateTime(dt.Date)), (" local_dt.Date", TDateTime(dt.Date))); }); [Fact] public async Task EvaluateStaticLocalsWithDeepMemberAccess() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dt = new DateTime(2020, 1, 2, 3, 4, 5); await EvaluateOnCallFrameAndCheck(id, ("f_s.c", TNumber(4)), ("f_s", TValueType("DebuggerTests.EvaluateTestsStructWithProperties")), ("f_s.dateTime", TDateTime(dt)), ("f_s.dateTime.Date", TDateTime(dt.Date))); }); [Fact] public async Task EvaluateLocalsAsync() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.Point", "AsyncInstanceMethod", 1, "MoveNext", "window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.ArrayTestsClass:EntryPointForStructMethod', true); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); // sc_arg { var (sc_arg, _) = await EvaluateOnCallFrame(id, "sc_arg"); await CheckValue(sc_arg, TObject("DebuggerTests.SimpleClass"), nameof(sc_arg)); // Check that we did get the correct object var sc_arg_props = await GetProperties(sc_arg["objectId"]?.Value<string>()); await CheckProps(sc_arg_props, new { X = TNumber(10), Y = TNumber(45), Id = TString("sc#Id"), Color = TEnum("DebuggerTests.RGB", "Blue"), PointWithCustomGetter = TGetter("PointWithCustomGetter") }, "sc_arg_props#1"); await EvaluateOnCallFrameAndCheck(id, ("(sc_arg.PointWithCustomGetter.X)", TNumber(100)), ("sc_arg.Id + \"_foo\"", TString($"sc#Id_foo")), ("sc_arg.Id + (sc_arg.X==10 ? \"_is_ten\" : \"_not_ten\")", TString($"sc#Id_is_ten"))); } // local_gs { var (local_gs, _) = await EvaluateOnCallFrame(id, "local_gs"); await CheckValue(local_gs, TValueType("DebuggerTests.SimpleGenericStruct<int>"), nameof(local_gs)); (local_gs, _) = await EvaluateOnCallFrame(id, " local_gs"); await CheckValue(local_gs, TValueType("DebuggerTests.SimpleGenericStruct<int>"), nameof(local_gs)); var local_gs_props = await GetProperties(local_gs["objectId"]?.Value<string>()); await CheckProps(local_gs_props, new { Id = TObject("string", is_null: true), Color = TEnum("DebuggerTests.RGB", "Red"), Value = TNumber(0) }, "local_gs_props#1"); await EvaluateOnCallFrameAndCheck(id, ("(local_gs.Id)", TString(null))); } }); [Theory] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsStructWithProperties")] [MemberData(nameof(InstanceMethodForTypeMembersTestData), parameters: "DebuggerTests.EvaluateTestsClassWithProperties")] public async Task EvaluateExpressionsWithDeepMemberAccesses(string prefix, int bias, string type, string method, string bp_function_name, bool _) => await CheckInspectLocalsAtBreakpointSite( type, method, /*line_offset*/4, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] {type}:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var dateTime = new DateTime(2010, 9, 8, 7, 6, 5 + bias); var DTProp = dateTime.AddMinutes(10); await EvaluateOnCallFrameAndCheck(id, ($"{prefix}a + 5", TNumber(9)), ($"10 + {prefix}IntProp", TNumber(19)), ($" {prefix}IntProp + {prefix}DTProp.Second", TNumber(9 + DTProp.Second)), ($" {prefix}IntProp + ({prefix}DTProp.Second+{prefix}dateTime.Year)", TNumber(9 + DTProp.Second + dateTime.Year)), ($" {prefix}DTProp.Second > 0 ? \"_foo_\": \"_zero_\"", TString("_foo_")), // local_dt is not live yet ($"local_dt.Date.Year * 10", TNumber(10))); }); [Theory] [InlineData("")] [InlineData("this.")] public async Task InheritedAndPrivateMembersInAClass(string prefix) => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.GetPropertiesTests.DerivedClass", "InstanceMethod", 1, "InstanceMethod", $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] DebuggerTests.GetPropertiesTests.DerivedClass:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); foreach (var pad in new[] { String.Empty, " " }) { var padded_prefix = pad + prefix; await EvaluateOnCallFrameAndCheck(id, // overridden ($"{padded_prefix}FirstName + \"_foo\"", TString("DerivedClass#FirstName_foo")), ($"{padded_prefix}DateTimeForOverride.Date.Year", TNumber(2190)), ($"{padded_prefix}DateTimeForOverride.Date.Year - 10", TNumber(2180)), ($"\"foo_\" + {padded_prefix}StringPropertyForOverrideWithAutoProperty", TString("foo_DerivedClass#StringPropertyForOverrideWithAutoProperty")), // private ($"{padded_prefix}_stringField + \"_foo\"", TString("DerivedClass#_stringField_foo")), ($"{padded_prefix}_stringField", TString("DerivedClass#_stringField")), ($"{padded_prefix}_dateTime.Second + 4", TNumber(7)), ($"{padded_prefix}_DTProp.Second + 4", TNumber(13)), // inherited public ($"\"foo_\" + {padded_prefix}Base_AutoStringProperty", TString("foo_base#Base_AutoStringProperty")), // inherited private ($"{padded_prefix}_base_dateTime.Date.Year - 10", TNumber(2124)) ); } }); [Fact] public async Task EvaluateSimpleExpressions() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, // "((this))", TObject("foo")); //FIXME: // "((dt))", TObject("foo")); //FIXME: ("this", TObject("DebuggerTests.EvaluateTestsClass.TestEvaluate")), (" this", TObject("DebuggerTests.EvaluateTestsClass.TestEvaluate")), ("5", TNumber(5)), (" 5", TNumber(5)), ("d + e", TNumber(203)), ("e + 10", TNumber(112)), // repeated expressions ("this.a + this.a", TNumber(2)), ("a + \"_\" + a", TString("9000_9000")), ("a+(a )", TString("90009000")), // possible duplicate arg name ("this.a + this_a", TNumber(46)), ("this.a + this.b", TNumber(3)), ("\"test\" + \"test\"", TString("testtest")), ("5 + 5", TNumber(10))); }); public static TheoryData<string, string, string> ShadowMethodArgsTestData => new TheoryData<string, string, string> { { "DebuggerTests.EvaluateTestsClassWithProperties", "EvaluateShadow", "EvaluateShadow" }, { "DebuggerTests.EvaluateTestsClassWithProperties", "EvaluateShadowAsync", "MoveNext" }, { "DebuggerTests.EvaluateTestsStructWithProperties", "EvaluateShadow", "EvaluateShadow" }, { "DebuggerTests.EvaluateTestsStructWithProperties", "EvaluateShadowAsync", "MoveNext" }, }; [Theory] [MemberData(nameof(ShadowMethodArgsTestData))] public async Task LocalsAndArgsShadowingThisMembers(string type_name, string method, string bp_function_name) => await CheckInspectLocalsAtBreakpointSite( type_name, method, 2, bp_function_name, "window.setTimeout(function() { invoke_static_method ('[debugger-test] " + type_name + ":run'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("a", TString("hello")), ("this.a", TNumber(4))); await CheckExpressions("this.", new DateTime(2010, 9, 8, 7, 6, 5 + 0)); await CheckExpressions(String.Empty, new DateTime(2020, 3, 4, 5, 6, 7)); async Task CheckExpressions(string prefix, DateTime dateTime) { await EvaluateOnCallFrameAndCheck(id, (prefix + "dateTime", TDateTime(dateTime)), (prefix + "dateTime.TimeOfDay.Minutes", TNumber(dateTime.TimeOfDay.Minutes)), (prefix + "dateTime.TimeOfDay", TValueType("System.TimeSpan", dateTime.TimeOfDay.ToString()))); } }); [Theory] [InlineData("DebuggerTests.EvaluateTestsStructWithProperties", true)] [InlineData("DebuggerTests.EvaluateTestsClassWithProperties", false)] public async Task EvaluateOnPreviousFrames(string type_name, bool is_valuetype) => await CheckInspectLocalsAtBreakpointSite( type_name, "EvaluateShadow", 1, "EvaluateShadow", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] {type_name}:run'); }})", wait_for_event_fn: async (pause_location) => { var dt_local = new DateTime(2020, 3, 4, 5, 6, 7); var dt_this = new DateTime(2010, 9, 8, 7, 6, 5); // At EvaluateShadow { var id0 = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id0, ("dateTime", TDateTime(dt_local)), ("this.dateTime", TDateTime(dt_this)) ); await EvaluateOnCallFrameFail(id0, ("obj.IntProp", "ReferenceError")); } { var id1 = pause_location["callFrames"][1]["callFrameId"].Value<string>(); await EvaluateOnCallFrameFail(id1, ("dateTime", "ReferenceError"), ("this.dateTime", "ReferenceError")); // obj available only on the -1 frame await EvaluateOnCallFrameAndCheck(id1, ("obj.IntProp", TNumber(7))); } await SetBreakpointInMethod("debugger-test.dll", type_name, "SomeMethod", 1); pause_location = await SendCommandAndCheck(null, "Debugger.resume", null, 0, 0, "SomeMethod"); // At SomeMethod // TODO: change types also.. so, that `this` is different! // Check frame0 { var id0 = pause_location["callFrames"][0]["callFrameId"].Value<string>(); // 'me' and 'dateTime' are reversed in this method await EvaluateOnCallFrameAndCheck(id0, ("dateTime", is_valuetype ? TValueType(type_name) : TObject(type_name)), ("this.dateTime", TDateTime(dt_this)), ("me", TDateTime(dt_local)), // local variable shadows field, but isn't "live" yet ("DTProp", TString(null)), // access field via `this.` ("this.DTProp", TDateTime(dt_this.AddMinutes(10)))); await EvaluateOnCallFrameFail(id0, ("obj", "ReferenceError")); } // check frame1 { var id1 = pause_location["callFrames"][1]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id1, // 'me' and 'dateTime' are reversed in this method ("dateTime", TDateTime(dt_local)), ("this.dateTime", TDateTime(dt_this)), ("me", is_valuetype ? TValueType(type_name) : TObject(type_name)), // not shadowed here ("DTProp", TDateTime(dt_this.AddMinutes(10))), // access field via `this.` ("this.DTProp", TDateTime(dt_this.AddMinutes(10)))); await EvaluateOnCallFrameFail(id1, ("obj", "ReferenceError")); } // check frame2 { var id2 = pause_location["callFrames"][2]["callFrameId"].Value<string>(); // Only obj should be available await EvaluateOnCallFrameFail(id2, ("dateTime", "ReferenceError"), ("this.dateTime", "ReferenceError"), ("me", "ReferenceError")); await EvaluateOnCallFrameAndCheck(id2, ("obj", is_valuetype ? TValueType(type_name) : TObject(type_name))); } }); [Fact] public async Task JSEvaluate() { var bp_loc = "/other.js"; var line = 78; var col = 1; await SetBreakpoint(bp_loc, line, col); var eval_expr = "window.setTimeout(function() { eval_call_on_frame_test (); }, 1)"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameFail(id, ("me.foo", null), ("obj.foo.bar", null)); await EvaluateOnCallFrame(id, "obj.foo", expect_ok: true); } [Fact] public async Task NegativeTestsInInstanceMethod() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); // Use '.' on a primitive member await EvaluateOnCallFrameFail(id, //BUG: TODO: //("a)", "CompilationError"), ("this.a.", "ReferenceError"), ("a.", "ReferenceError"), ("this..a", "CompilationError"), (".a.", "ReferenceError"), ("me.foo", "ReferenceError"), ("this.a + non_existant", "ReferenceError"), ("this.NullIfAIsNotZero.foo", "ReferenceError"), ("NullIfAIsNotZero.foo", "ReferenceError")); }); [Fact] public async Task NegativeTestsInStaticMethod() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameFail(id, ("me.foo", "ReferenceError"), ("this", "CompilationError"), ("this.NullIfAIsNotZero.foo", "ReferenceError")); }); [Fact] public async Task EvaluatePropertyThatThrows() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClassWithProperties", "InstanceMethod", /*line_offset*/1, "InstanceMethod", $"window.setTimeout(function() {{ invoke_static_method_async('[debugger-test] DebuggerTests.EvaluateTestsClassWithProperties:run');}}, 1);", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.PropertyThrowException", TString("System.Exception: error"))); }); async Task EvaluateOnCallFrameFail(string call_frame_id, params (string expression, string class_name)[] args) { foreach (var arg in args) { var (_, res) = await EvaluateOnCallFrame(call_frame_id, arg.expression, expect_ok: false); if (arg.class_name != null) AssertEqual(arg.class_name, res.Error["result"]?["className"]?.Value<string>(), $"Error className did not match for expression '{arg.expression}'"); } } [Fact] [Trait("Category", "windows-failing")] // https://github.com/dotnet/runtime/issues/65744 [Trait("Category", "linux-failing")] // https://github.com/dotnet/runtime/issues/65744 public async Task EvaluateSimpleMethodCallsError() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (_, res) = await EvaluateOnCallFrame(id, "this.objToTest.MyMethodWrong()", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethodWrong'", res.Error["message"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.objToTest.MyMethod(1)", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethod'. Too many arguments passed.", res.Error["result"]["description"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.CallMethodWithParm(\"1\")", expect_ok: false ); AssertEqual("Unable to evaluate method 'CallMethodWithParm'", res.Error["message"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.ParmToTestObjNull.MyMethod()", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethod'", res.Error["message"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "this.ParmToTestObjException.MyMethod()", expect_ok: false ); AssertEqual("Unable to evaluate method 'MyMethod'", res.Error["message"]?.Value<string>(), "wrong error message"); }); [Fact] public async Task EvaluateSimpleMethodCallsWithoutParms() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethod()", TNumber(1)), ("this.CallMethod()", TNumber(1)), ("this.CallMethodReturningChar()", TChar('A')), ("this.ParmToTestObj.MyMethod()", TString("methodOK")), ("this.ParmToTestObj.ToString()", TString("DebuggerTests.EvaluateMethodTestsClass+ParmToTest")), ("this.objToTest.MyMethod()", TString("methodOK"))); }); [Fact] public async Task EvaluateSimpleMethodCallsWithConstParms() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethodWithParm(10)", TNumber(11)), ("this.CallMethodWithMultipleParms(10, 10)", TNumber(21)), ("this.CallMethodWithParmBool(true)", TString("TRUE")), ("this.CallMethodWithParmBool(false)", TString("FALSE")), ("this.CallMethodWithParmString(\"concat\")", TString("str_const_concat")), ("this.CallMethodWithParmString(\"\\\"\\\"\")", TString("str_const_\"\"")), ("this.CallMethodWithParmString(\"🛶\")", TString("str_const_🛶")), ("this.CallMethodWithParmString(\"\\uD83D\\uDEF6\")", TString("str_const_🛶")), ("this.CallMethodWithParmString(\"🚀\")", TString("str_const_🚀")), ("this.CallMethodWithParmString_λ(\"🚀\")", TString("λ_🚀")), ("this.CallMethodWithParm(10) + this.a", TNumber(12)), ("this.CallMethodWithObj(null)", TNumber(-1)), ("this.CallMethodWithChar('a')", TString("str_const_a"))); }); [Fact] public async Task EvaluateSimpleMethodCallsWithVariableParms() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethodWithParm(this.a)", TNumber(2)), ("this.CallMethodWithMultipleParms(this.a, 10)", TNumber(12)), ("this.CallMethodWithParmString(this.str)", TString("str_const_str_const_")), ("this.CallMethodWithParmBool(this.t)", TString("TRUE")), ("this.CallMethodWithParmBool(this.f)", TString("FALSE")), ("this.CallMethodWithParm(this.a) + this.a", TNumber(3)), ("this.CallMethodWithObj(this.objToTest)", TNumber(10))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessByConstant() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.numList[0]", TNumber(1)), ("f.textList[1]", TString("2")), ("f.numArray[1]", TNumber(2)), ("f.textArray[0]", TString("1"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessByLocalVariable() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.numList[i]", TNumber(1)), ("f.textList[j]", TString("2")), ("f.numArray[j]", TNumber(2)), ("f.textArray[i]", TString("1"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessByMemberVariables() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.idx0", TNumber(0)), ("f.idx1", TNumber(1)), ("f.numList[f.idx0]", TNumber(1)), ("f.textList[f.idx1]", TString("2")), ("f.numArray[f.idx1]", TNumber(2)), ("f.textArray[f.idx0]", TString("1"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessNested() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("f.idx0", TNumber(0)), ("f.numList[f.numList[f.idx0]]", TNumber(2)), ("f.textList[f.numList[f.idx0]]", TString("2")), ("f.numArray[f.numArray[f.idx0]]", TNumber(2)), ("f.textArray[f.numArray[f.idx0]]", TString("2"))); }); [Fact] public async Task EvaluateExpressionsWithElementAccessMultidimentional() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateLocalsWithElementAccessTests", "EvaluateLocals", 5, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateLocalsWithElementAccessTests:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("j", TNumber(1)), ("f.idx1", TNumber(1)), ("f.numArrayOfArrays[1][1]", TNumber(2)), ("f.numArrayOfArrays[j][j]", TNumber(2)), ("f.numArrayOfArrays[f.idx1][f.idx1]", TNumber(2)), ("f.numListOfLists[1][1]", TNumber(2)), ("f.numListOfLists[j][j]", TNumber(2)), ("f.numListOfLists[f.idx1][f.idx1]", TNumber(2)), ("f.textArrayOfArrays[1][1]", TString("2")), ("f.textArrayOfArrays[j][j]", TString("2")), ("f.textArrayOfArrays[f.idx1][f.idx1]", TString("2")), ("f.textListOfLists[1][1]", TString("2")), ("f.textListOfLists[j][j]", TString("2")), ("f.textListOfLists[f.idx1][f.idx1]", TString("2"))); }); [Fact] public async Task EvaluateSimpleMethodCallsCheckChangedValue() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; var props = await GetObjectOnFrame(frame, "this"); CheckNumber(props, "a", 1); await EvaluateOnCallFrameAndCheck(id, ("this.CallMethodChangeValue()", TObject("object", is_null : true))); frame = pause_location["callFrames"][0]; props = await GetObjectOnFrame(frame, "this"); CheckNumber(props, "a", 11); }); [Fact] public async Task EvaluateStaticClass() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.StaticField1", TNumber(10))); await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.StaticProperty1", TString("StaticProperty1"))); await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Theory] [MemberData(nameof(EvaluateStaticClassFromStaticMethodTestData), parameters: "DebuggerTests.EvaluateMethodTestsClass")] // [MemberData(nameof(EvaluateStaticClassFromStaticMethodTestData), parameters: "EvaluateMethodTestsClass")] public async Task EvaluateStaticClassFromStaticMethod(string type, string method, string bp_function_name, bool is_async) => await CheckInspectLocalsAtBreakpointSite( type, method, 1, bp_function_name, $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] {type}:{method}'); }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("EvaluateStaticClass.StaticField1", TNumber(10)), ("EvaluateStaticClass.StaticProperty1", TString("StaticProperty1")), ("EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented")), ("DebuggerTests.EvaluateStaticClass.StaticField1", TNumber(10)), ("DebuggerTests.EvaluateStaticClass.StaticProperty1", TString("StaticProperty1")), ("DebuggerTests.EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Fact] public async Task EvaluateNonStaticClassWithStaticFields() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass", "EvaluateAsyncMethods", 3, "EvaluateAsyncMethods", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateAsyncMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateNonStaticClassWithStaticFields.StaticField1", TNumber(10)), ("DebuggerTests.EvaluateNonStaticClassWithStaticFields.StaticProperty1", TString("StaticProperty1")), ("DebuggerTests.EvaluateNonStaticClassWithStaticFields.StaticPropertyWithError", TString("System.Exception: not implemented")), ("EvaluateNonStaticClassWithStaticFields.StaticField1", TNumber(10)), ("EvaluateNonStaticClassWithStaticFields.StaticProperty1", TString("StaticProperty1")), ("EvaluateNonStaticClassWithStaticFields.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Fact] public async Task EvaluateStaticClassesNested() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass", "EvaluateMethods", 3, "EvaluateMethods", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("DebuggerTests.EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticField1", TNumber(3)), ("DebuggerTests.EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticProperty1", TString("StaticProperty3")), ("DebuggerTests.EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticPropertyWithError", TString("System.Exception: not implemented 3")), ("EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticField1", TNumber(3)), ("EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticProperty1", TString("StaticProperty3")), ("EvaluateStaticClass.NestedClass1.NestedClass2.NestedClass3.StaticPropertyWithError", TString("System.Exception: not implemented 3"))); }); [Fact] public async Task EvaluateStaticClassesNestedWithNoNamespace() => await CheckInspectLocalsAtBreakpointSite( "NoNamespaceClass", "EvaluateMethods", 1, "EvaluateMethods", "window.setTimeout(function() { invoke_static_method ('[debugger-test] NoNamespaceClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id, ("NoNamespaceClass.NestedClass1.NestedClass2.NestedClass3.StaticField1", TNumber(30)), ("NoNamespaceClass.NestedClass1.NestedClass2.NestedClass3.StaticProperty1", TString("StaticProperty30")), ("NoNamespaceClass.NestedClass1.NestedClass2.NestedClass3.StaticPropertyWithError", TString("System.Exception: not implemented 30"))); }); [Fact] public async Task EvaluateStaticClassesFromDifferentNamespaceInDifferentFrames() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTestsV2.EvaluateStaticClass", "Run", 1, "Run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id_top = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; await EvaluateOnCallFrameAndCheck(id_top, ("EvaluateStaticClass.StaticField1", TNumber(20)), ("EvaluateStaticClass.StaticProperty1", TString("StaticProperty2")), ("EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); var id_second = pause_location["callFrames"][1]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id_second, ("EvaluateStaticClass.StaticField1", TNumber(10)), ("EvaluateStaticClass.StaticProperty1", TString("StaticProperty1")), ("EvaluateStaticClass.StaticPropertyWithError", TString("System.Exception: not implemented"))); }); [Fact] public async Task EvaluateStaticClassInvalidField() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateMethodTestsClass.TestEvaluate", "run", 9, "run", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateMethodTestsClass:EvaluateMethods'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame = pause_location["callFrames"][0]; var (_, res) = await EvaluateOnCallFrame(id, "DebuggerTests.EvaluateStaticClass.StaticProperty2", expect_ok: false); AssertEqual("Failed to resolve member access for DebuggerTests.EvaluateStaticClass.StaticProperty2", res.Error["result"]?["description"]?.Value<string>(), "wrong error message"); (_, res) = await EvaluateOnCallFrame(id, "DebuggerTests.InvalidEvaluateStaticClass.StaticProperty2", expect_ok: false); AssertEqual("Failed to resolve member access for DebuggerTests.InvalidEvaluateStaticClass.StaticProperty2", res.Error["result"]?["description"]?.Value<string>(), "wrong error message"); }); [Fact] public async Task AsyncLocalsInContinueWithBlock() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.AsyncTests.ContinueWithTests", "ContinueWithStaticAsync", 4, "<ContinueWithStaticAsync>b__3_0", "window.setTimeout(function() { invoke_static_method('[debugger-test] DebuggerTests.AsyncTests.ContinueWithTests:RunAsync'); })", wait_for_event_fn: async (pause_location) => { var frame_locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value<string>()); var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ($"t.Status", TEnum("System.Threading.Tasks.TaskStatus", "RanToCompletion")), ($" t.Status", TEnum("System.Threading.Tasks.TaskStatus", "RanToCompletion")) ); await EvaluateOnCallFrameFail(id, ("str", "ReferenceError"), (" str", "ReferenceError") ); }); [Fact] public async Task EvaluateConstantValueUsingRuntimeEvaluate() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { var dt = new DateTime(2020, 1, 2, 3, 4, 5); await RuntimeEvaluateAndCheck( ("15\n//comment as vs does\n", TNumber(15)), ("15", TNumber(15)), ("\"15\"\n//comment as vs does\n", TString("15")), ("\"15\"", TString("15"))); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsNone", "testFieldsNone", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesNone", "testPropertiesNone", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesNone", "testPropertiesNone", 5, true)] public async Task EvaluateBrowsableNone(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testNone, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testNone, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testNone)); var testNoneProps = await GetProperties(testNone["objectId"]?.Value<string>()); if (isCustomGetter) await CheckProps(testNoneProps, new { list = TGetter("list", TObject("System.Collections.Generic.List<int>", description: "Count = 2")), array = TGetter("array", TObject("int[]", description: "int[2]")), text = TGetter("text", TString("text")) }, "testNoneProps#1"); else await CheckProps(testNoneProps, new { list = TObject("System.Collections.Generic.List<int>", description: "Count = 2"), array = TObject("int[]", description: "int[2]"), text = TString("text") }, "testNoneProps#1"); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsNever", "testFieldsNever", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsNever", "testFieldsNever", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 5)] public async Task EvaluateBrowsableNever(string outerClassName, string className, string localVarName, int breakLine) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testNever, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testNever, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testNever)); var testNeverProps = await GetProperties(testNever["objectId"]?.Value<string>()); await CheckProps(testNeverProps, new { }, "testNeverProps#1"); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsCollapsed", "testFieldsCollapsed", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsCollapsed", "testFieldsCollapsed", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 5, true)] public async Task EvaluateBrowsableCollapsed(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testCollapsed, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testCollapsed, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testCollapsed)); var testCollapsedProps = await GetProperties(testCollapsed["objectId"]?.Value<string>()); if (isCustomGetter) await CheckProps(testCollapsedProps, new { listCollapsed = TGetter("listCollapsed", TObject("System.Collections.Generic.List<int>", description: "Count = 2")), arrayCollapsed = TGetter("arrayCollapsed", TObject("int[]", description: "int[2]")), textCollapsed = TGetter("textCollapsed", TString("textCollapsed")) }, "testCollapsedProps#1"); else await CheckProps(testCollapsedProps, new { listCollapsed = TObject("System.Collections.Generic.List<int>", description: "Count = 2"), arrayCollapsed = TObject("int[]", description: "int[2]"), textCollapsed = TString("textCollapsed") }, "testCollapsedProps#1"); }); [Theory] [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsRootHidden", "testFieldsRootHidden", 10)] [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsRootHidden", "testFieldsRootHidden", 10)] [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 10)] [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 5, true)] public async Task EvaluateBrowsableRootHidden(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (testRootHidden, _) = await EvaluateOnCallFrame(id, localVarName); await CheckValue(testRootHidden, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testRootHidden)); var testRootHiddenProps = await GetProperties(testRootHidden["objectId"]?.Value<string>()); var (refList, _) = await EvaluateOnCallFrame(id, "testPropertiesNone.list"); var refListProp = await GetProperties(refList["objectId"]?.Value<string>()); var refListElementsProp = await GetProperties(refListProp[0]["value"]["objectId"]?.Value<string>()); var (refArray, _) = await EvaluateOnCallFrame(id, "testPropertiesNone.array"); var refArrayProp = await GetProperties(refArray["objectId"]?.Value<string>()); //in Console App names are in [] //adding variable name to make elements unique foreach (var item in refArrayProp) { item["name"] = string.Concat("arrayRootHidden[", item["name"], "]"); } foreach (var item in refListElementsProp) { item["name"] = string.Concat("listRootHidden[", item["name"], "]"); } var mergedRefItems = new JArray(refListElementsProp.Union(refArrayProp)); Assert.Equal(mergedRefItems, testRootHiddenProps); }); [Fact] public async Task EvaluateStaticAttributeInAssemblyNotRelatedButLoaded() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocals", 9, "EvaluateLocals", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })", wait_for_event_fn: async (pause_location) => { await RuntimeEvaluateAndCheck( ("ClassToBreak.valueToCheck", TNumber(10))); }); [Fact] public async Task EvaluateLocalObjectFromAssemblyNotRelatedButLoaded() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateTestsClass", "EvaluateLocalsFromAnotherAssembly", 5, "EvaluateLocalsFromAnotherAssembly", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocalsFromAnotherAssembly'); })", wait_for_event_fn: async (pause_location) => { await RuntimeEvaluateAndCheck( ("a.valueToCheck", TNumber(20))); }); [Fact] public async Task EvaluateProtectionLevels() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.EvaluateProtectionLevels", "Evaluate", 2, "Evaluate", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.EvaluateProtectionLevels:Evaluate'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (obj, _) = await EvaluateOnCallFrame(id, "testClass"); var (pub, internalAndProtected, priv) = await GetPropertiesSortedByProtectionLevels(obj["objectId"]?.Value<string>()); Assert.True(pub[0] != null); Assert.True(internalAndProtected[0] != null); Assert.True(internalAndProtected[1] != null); Assert.True(priv[0] != null); Assert.Equal(pub[0]["value"]["value"], "public"); Assert.Equal(internalAndProtected[0]["value"]["value"], "internal"); Assert.Equal(internalAndProtected[1]["value"]["value"], "protected"); Assert.Equal(priv[0]["value"]["value"], "private"); }); [Fact] public async Task StructureGetters() => await CheckInspectLocalsAtBreakpointSite( "DebuggerTests.StructureGetters", "Evaluate", 2, "Evaluate", "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.StructureGetters:Evaluate'); })", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var (obj, _) = await EvaluateOnCallFrame(id, "s"); var props = await GetProperties(obj["objectId"]?.Value<string>()); await CheckProps(props, new { Id = TGetter("Id", TNumber(123)) }, "s#1"); var getter = props.FirstOrDefault(p => p["name"]?.Value<string>() == "Id"); Assert.NotNull(getter); var getterId = getter["get"]["objectId"]?.Value<string>(); var getterProps = await GetProperties(getterId); Assert.Equal(getterProps[0]?["value"]?["value"]?.Value<int>(), 123); }); [Fact] public async Task EvaluateMethodWithDefaultParam() => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.DefaultParamMethods", "Evaluate", 2, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.DefaultParamMethods:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("test.GetByte()", TNumber(1)), ("test.GetSByte()", TNumber(1)), ("test.GetByteNullable()", TNumber(1)), ("test.GetSByteNullable()", TNumber(1)), ("test.GetInt16()", TNumber(1)), ("test.GetUInt16()", TNumber(1)), ("test.GetInt16Nullable()", TNumber(1)), ("test.GetUInt16Nullable()", TNumber(1)), ("test.GetInt32()", TNumber(1)), ("test.GetUInt32()", TNumber(1)), ("test.GetInt32Nullable()", TNumber(1)), ("test.GetUInt32Nullable()", TNumber(1)), ("test.GetInt64()", TNumber(1)), ("test.GetUInt64()", TNumber(1)), ("test.GetInt64Nullable()", TNumber(1)), ("test.GetUInt64Nullable()", TNumber(1)), ("test.GetChar()", TChar('T')), ("test.GetCharNullable()", TChar('T')), ("test.GetUnicodeChar()", TChar('ą')), ("test.GetString()", TString("1.23")), ("test.GetUnicodeString()", TString("żółć")), ("test.GetString(null)", TObject("string", is_null: true)), ("test.GetStringNullable()", TString("1.23")), ("test.GetSingle()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetDouble()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetSingleNullable()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetDoubleNullable()", JObject.FromObject( new { type = "number", value = 1.23, description = "1.23" })), ("test.GetBool()", JObject.FromObject( new { type = "object", value = true, description = "True", className = "System.Boolean" })), ("test.GetBoolNullable()", JObject.FromObject( new { type = "object", value = true, description = "True", className = "System.Boolean" })), ("test.GetNull()", JObject.FromObject( new { type = "object", value = true, description = "True", className = "System.Boolean" })), ("test.GetDefaultAndRequiredParam(2)", TNumber(5)), ("test.GetDefaultAndRequiredParam(3, 2)", TNumber(5)), ("test.GetDefaultAndRequiredParamMixedTypes(\"a\")", TString("a; -1; False")), ("test.GetDefaultAndRequiredParamMixedTypes(\"a\", 23)", TString("a; 23; False")), ("test.GetDefaultAndRequiredParamMixedTypes(\"a\", 23, true)", TString("a; 23; True")) ); var (_, res) = await EvaluateOnCallFrame(id, "test.GetDefaultAndRequiredParamMixedTypes(\"a\", 23, true, 1.23f)", expect_ok: false ); AssertEqual("Unable to evaluate method 'GetDefaultAndRequiredParamMixedTypes'. Too many arguments passed.", res.Error["result"]["description"]?.Value<string>(), "wrong error message"); }); [Fact] public async Task EvaluateMethodWithLinq() => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.DefaultParamMethods", "Evaluate", 2, "Evaluate", $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.DefaultParamMethods:Evaluate'); 1 }})", wait_for_event_fn: async (pause_location) => { var id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); await EvaluateOnCallFrameAndCheck(id, ("test.listToLinq.ToList()", TObject("System.Collections.Generic.List<int>", description: "Count = 11")) ); }); } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Linq.Expressions/tests/TrimmingTests/BinaryOperatorTests.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.Linq.Expressions; /// <summary> /// Tests that Expression.Add expressions still work correctly and find /// the + operator in a trimmed app. /// </summary> internal class Program { static int Main(string[] args) { ParameterExpression leftParameter = Expression.Parameter(typeof(Class1)); ParameterExpression rightParameter = Expression.Parameter(typeof(Class1)); ParameterExpression result = Expression.Variable(typeof(Class1)); Func<Class1, Class1, Class1> func = Expression.Lambda<Func<Class1, Class1, Class1>>( Expression.Block( new[] { result }, Expression.Assign(result, Expression.Add(leftParameter, rightParameter)), result), leftParameter, rightParameter) .Compile(); Class1 actual = func(new Class1("left"), new Class1("right")); if (actual.Name != "left+right") { return -1; } // make sure Class2 was trimmed since it wasn't used, even though Class1 has a binary operator using it int i = 2; if (typeof(Program).Assembly.GetType("Class" + i) != null) { return -2; } return 100; } } internal class Class1 { public Class1(string name) => Name = name; public string Name { get; set; } public static Class1 operator +(Class1 left, Class1 right) => new Class1($"{left.Name}+{right.Name}"); public static Class1 operator +(Class1 left, Class2 right) => new Class1($"{left.Name}+{right.Name}2"); public static Class2 operator +(Class2 left, Class1 right) => new Class2($"{left.Name}2+{right.Name}"); } internal class Class2 { public Class2(string name) => Name = name; public string Name { get; set; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq.Expressions; /// <summary> /// Tests that Expression.Add expressions still work correctly and find /// the + operator in a trimmed app. /// </summary> internal class Program { static int Main(string[] args) { ParameterExpression leftParameter = Expression.Parameter(typeof(Class1)); ParameterExpression rightParameter = Expression.Parameter(typeof(Class1)); ParameterExpression result = Expression.Variable(typeof(Class1)); Func<Class1, Class1, Class1> func = Expression.Lambda<Func<Class1, Class1, Class1>>( Expression.Block( new[] { result }, Expression.Assign(result, Expression.Add(leftParameter, rightParameter)), result), leftParameter, rightParameter) .Compile(); Class1 actual = func(new Class1("left"), new Class1("right")); if (actual.Name != "left+right") { return -1; } // make sure Class2 was trimmed since it wasn't used, even though Class1 has a binary operator using it int i = 2; if (typeof(Program).Assembly.GetType("Class" + i) != null) { return -2; } return 100; } } internal class Class1 { public Class1(string name) => Name = name; public string Name { get; set; } public static Class1 operator +(Class1 left, Class1 right) => new Class1($"{left.Name}+{right.Name}"); public static Class1 operator +(Class1 left, Class2 right) => new Class1($"{left.Name}+{right.Name}2"); public static Class2 operator +(Class2 left, Class1 right) => new Class2($"{left.Name}2+{right.Name}"); } internal class Class2 { public Class2(string name) => Name = name; public string Name { get; set; } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net.Cache; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Net.Sockets; using System.Runtime.Serialization; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net { public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders); public class HttpWebRequest : WebRequest, ISerializable { private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop. private const int DefaultReadWriteTimeout = 5 * 60 * 1000; // 5 minutes private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection(); private readonly Uri _requestUri = null!; private string _originVerb = HttpMethod.Get.Method; // We allow getting and setting this (to preserve app-compat). But we don't do anything with it // as the underlying System.Net.Http API doesn't support it. private int _continueTimeout = DefaultContinueTimeout; private bool _allowReadStreamBuffering; private CookieContainer? _cookieContainer; private ICredentials? _credentials; private IWebProxy? _proxy = WebRequest.DefaultWebProxy; private Task<HttpResponseMessage>? _sendRequestTask; private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private int _beginGetRequestStreamCalled; private int _beginGetResponseCalled; private int _endGetRequestStreamCalled; private int _endGetResponseCalled; private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maximumResponseHeadersLen = _defaultMaxResponseHeadersLength; private ServicePoint? _servicePoint; private int _timeout = WebRequest.DefaultTimeoutMilliseconds; private int _readWriteTimeout = DefaultReadWriteTimeout; private HttpContinueDelegate? _continueDelegate; // stores the user provided Host header as Uri. If the user specified a default port explicitly we'll lose // that information when converting the host string to a Uri. _HostHasPort will store that information. private bool _hostHasPort; private Uri? _hostUri; private RequestStream? _requestStream; private TaskCompletionSource<Stream>? _requestStreamOperation; private TaskCompletionSource<WebResponse>? _responseOperation; private AsyncCallback? _requestStreamCallback; private AsyncCallback? _responseCallback; private int _abortCalled; private CancellationTokenSource? _sendRequestCts; private X509CertificateCollection? _clientCertificates; private Booleans _booleans = Booleans.Default; private bool _pipelined = true; private bool _preAuthenticate; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private static readonly object s_syncRoot = new object(); private static volatile HttpClient? s_cachedHttpClient; private static HttpClientParameters? s_cachedHttpClientParameters; //these should be safe. [Flags] private enum Booleans : uint { AllowAutoRedirect = 0x00000001, AllowWriteStreamBuffering = 0x00000002, ExpectContinue = 0x00000004, ProxySet = 0x00000010, UnsafeAuthenticatedConnectionSharing = 0x00000040, IsVersionHttp10 = 0x00000080, SendChunked = 0x00000100, EnableDecompression = 0x00000200, IsTunnelRequest = 0x00000400, IsWebSocketRequest = 0x00000800, Default = AllowAutoRedirect | AllowWriteStreamBuffering | ExpectContinue } private sealed class HttpClientParameters { public readonly bool Async; public readonly DecompressionMethods AutomaticDecompression; public readonly bool AllowAutoRedirect; public readonly int MaximumAutomaticRedirections; public readonly int MaximumResponseHeadersLength; public readonly bool PreAuthenticate; public readonly int ReadWriteTimeout; public readonly TimeSpan Timeout; public readonly SecurityProtocolType SslProtocols; public readonly bool CheckCertificateRevocationList; public readonly ICredentials? Credentials; public readonly IWebProxy? Proxy; public readonly RemoteCertificateValidationCallback? ServerCertificateValidationCallback; public readonly X509CertificateCollection? ClientCertificates; public readonly CookieContainer? CookieContainer; public HttpClientParameters(HttpWebRequest webRequest, bool async) { Async = async; AutomaticDecompression = webRequest.AutomaticDecompression; AllowAutoRedirect = webRequest.AllowAutoRedirect; MaximumAutomaticRedirections = webRequest.MaximumAutomaticRedirections; MaximumResponseHeadersLength = webRequest.MaximumResponseHeadersLength; PreAuthenticate = webRequest.PreAuthenticate; ReadWriteTimeout = webRequest.ReadWriteTimeout; Timeout = webRequest.Timeout == Threading.Timeout.Infinite ? Threading.Timeout.InfiniteTimeSpan : TimeSpan.FromMilliseconds(webRequest.Timeout); SslProtocols = ServicePointManager.SecurityProtocol; CheckCertificateRevocationList = ServicePointManager.CheckCertificateRevocationList; Credentials = webRequest._credentials; Proxy = webRequest._proxy; ServerCertificateValidationCallback = webRequest.ServerCertificateValidationCallback ?? ServicePointManager.ServerCertificateValidationCallback; ClientCertificates = webRequest._clientCertificates; CookieContainer = webRequest._cookieContainer; } public bool Matches(HttpClientParameters requestParameters) { return Async == requestParameters.Async && AutomaticDecompression == requestParameters.AutomaticDecompression && AllowAutoRedirect == requestParameters.AllowAutoRedirect && MaximumAutomaticRedirections == requestParameters.MaximumAutomaticRedirections && MaximumResponseHeadersLength == requestParameters.MaximumResponseHeadersLength && PreAuthenticate == requestParameters.PreAuthenticate && ReadWriteTimeout == requestParameters.ReadWriteTimeout && Timeout == requestParameters.Timeout && SslProtocols == requestParameters.SslProtocols && CheckCertificateRevocationList == requestParameters.CheckCertificateRevocationList && ReferenceEquals(Credentials, requestParameters.Credentials) && ReferenceEquals(Proxy, requestParameters.Proxy) && ReferenceEquals(ServerCertificateValidationCallback, requestParameters.ServerCertificateValidationCallback) && ReferenceEquals(ClientCertificates, requestParameters.ClientCertificates) && ReferenceEquals(CookieContainer, requestParameters.CookieContainer); } public bool AreParametersAcceptableForCaching() { return Credentials == null && ReferenceEquals(Proxy, DefaultWebProxy) && ServerCertificateValidationCallback == null && ClientCertificates == null && CookieContainer == null; } } private const string ContinueHeader = "100-continue"; private const string ChunkedHeader = "chunked"; [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { throw new PlatformNotSupportedException(); } [Obsolete("Serialization has been deprecated for HttpWebRequest.")] void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(); } [Obsolete("Serialization has been deprecated for HttpWebRequest.")] protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(); } internal HttpWebRequest(Uri uri) { _requestUri = uri; } private void SetSpecialHeaders(string HeaderName, string? value) { _webHeaderCollection.Remove(HeaderName); if (!string.IsNullOrEmpty(value)) { _webHeaderCollection[HeaderName] = value; } } public string? Accept { get { return _webHeaderCollection[HttpKnownHeaderNames.Accept]; } set { SetSpecialHeaders(HttpKnownHeaderNames.Accept, value); } } public virtual bool AllowReadStreamBuffering { get { return _allowReadStreamBuffering; } set { _allowReadStreamBuffering = value; } } public int MaximumResponseHeadersLength { get => _maximumResponseHeadersLen; set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_toosmall); } _maximumResponseHeadersLen = value; } } public int MaximumAutomaticRedirections { get { return _maximumAllowedRedirections; } set { if (value <= 0) { throw new ArgumentException(SR.net_toosmall, nameof(value)); } _maximumAllowedRedirections = value; } } public override string? ContentType { get { return _webHeaderCollection[HttpKnownHeaderNames.ContentType]; } set { SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value); } } public int ContinueTimeout { get { return _continueTimeout; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if ((value < 0) && (value != System.Threading.Timeout.Infinite)) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } _continueTimeout = value; } } public override int Timeout { get { return _timeout; } set { if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } _timeout = value; } } public override long ContentLength { get { long value; long.TryParse(_webHeaderCollection[HttpKnownHeaderNames.ContentLength], out value); return value; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall); } SetSpecialHeaders(HttpKnownHeaderNames.ContentLength, value.ToString()); } } public Uri Address { get { return _requestUri; } } public string? UserAgent { get { return _webHeaderCollection[HttpKnownHeaderNames.UserAgent]; } set { SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value); } } public string Host { get { Uri hostUri = _hostUri ?? Address; return (_hostUri == null || !_hostHasPort) && Address.IsDefaultPort ? hostUri.Host : hostUri.Host + ":" + hostUri.Port; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } ArgumentNullException.ThrowIfNull(value); Uri? hostUri; if ((value.Contains('/')) || (!TryGetHostUri(value, out hostUri))) { throw new ArgumentException(SR.net_invalid_host, nameof(value)); } _hostUri = hostUri; // Determine if the user provided string contains a port if (!_hostUri.IsDefaultPort) { _hostHasPort = true; } else if (!value.Contains(':')) { _hostHasPort = false; } else { int endOfIPv6Address = value.IndexOf(']'); _hostHasPort = endOfIPv6Address == -1 || value.LastIndexOf(':') > endOfIPv6Address; } } } public bool Pipelined { get { return _pipelined; } set { _pipelined = value; } } /// <devdoc> /// <para> /// Gets or sets the value of the Referer header. /// </para> /// </devdoc> public string? Referer { get { return _webHeaderCollection[HttpKnownHeaderNames.Referer]; } set { SetSpecialHeaders(HttpKnownHeaderNames.Referer, value); } } /// <devdoc> /// <para>Sets the media type header</para> /// </devdoc> public string? MediaType { get; set; } /// <devdoc> /// <para> /// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out. /// </para> /// </devdoc> public string? TransferEncoding { get { return _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding]; } set { bool fChunked; // // on blank string, remove current header // if (string.IsNullOrWhiteSpace(value)) { // // if the value is blank, then remove the header // _webHeaderCollection.Remove(HttpKnownHeaderNames.TransferEncoding); return; } // // if not check if the user is trying to set chunked: // fChunked = (value.IndexOf(ChunkedHeader, StringComparison.OrdinalIgnoreCase) != -1); // // prevent them from adding chunked, or from adding an Encoding without // turning on chunked, the reason is due to the HTTP Spec which prevents // additional encoding types from being used without chunked // if (fChunked) { throw new ArgumentException(SR.net_nochunked, nameof(value)); } else if (!SendChunked) { throw new InvalidOperationException(SR.net_needchunked); } else { string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value); _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding] = checkedValue; } } } public bool KeepAlive { get; set; } = true; public bool UnsafeAuthenticatedConnectionSharing { get { return (_booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != 0; } set { if (value) { _booleans |= Booleans.UnsafeAuthenticatedConnectionSharing; } else { _booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing; } } } public DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } _automaticDecompression = value; } } public virtual bool AllowWriteStreamBuffering { get { return (_booleans & Booleans.AllowWriteStreamBuffering) != 0; } set { if (value) { _booleans |= Booleans.AllowWriteStreamBuffering; } else { _booleans &= ~Booleans.AllowWriteStreamBuffering; } } } /// <devdoc> /// <para> /// Enables or disables automatically following redirection responses. /// </para> /// </devdoc> public virtual bool AllowAutoRedirect { get { return (_booleans & Booleans.AllowAutoRedirect) != 0; } set { if (value) { _booleans |= Booleans.AllowAutoRedirect; } else { _booleans &= ~Booleans.AllowAutoRedirect; } } } public override string? ConnectionGroupName { get; set; } public override bool PreAuthenticate { get { return _preAuthenticate; } set { _preAuthenticate = value; } } public string? Connection { get { return _webHeaderCollection[HttpKnownHeaderNames.Connection]; } set { bool fKeepAlive; bool fClose; // // on blank string, remove current header // if (string.IsNullOrWhiteSpace(value)) { _webHeaderCollection.Remove(HttpKnownHeaderNames.Connection); return; } fKeepAlive = (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1); fClose = (value.IndexOf("close", StringComparison.OrdinalIgnoreCase) != -1); // // Prevent keep-alive and close from being added // if (fKeepAlive || fClose) { throw new ArgumentException(SR.net_connarg, nameof(value)); } else { string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value); _webHeaderCollection[HttpKnownHeaderNames.Connection] = checkedValue; } } } /* Accessor: Expect The property that controls the Expect header Input: string Expect, null clears the Expect except for 100-continue value Returns: The value of the Expect on get. */ public string? Expect { get { return _webHeaderCollection[HttpKnownHeaderNames.Expect]; } set { // only remove everything other than 100-cont bool fContinue100; // // on blank string, remove current header // if (string.IsNullOrWhiteSpace(value)) { _webHeaderCollection.Remove(HttpKnownHeaderNames.Expect); return; } // // Prevent 100-continues from being added // fContinue100 = (value.IndexOf(ContinueHeader, StringComparison.OrdinalIgnoreCase) != -1); if (fContinue100) { throw new ArgumentException(SR.net_no100, nameof(value)); } else { string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value); _webHeaderCollection[HttpKnownHeaderNames.Expect] = checkedValue; } } } /// <devdoc> /// <para> /// Gets or sets the default for the MaximumResponseHeadersLength property. /// </para> /// <remarks> /// This value can be set in the config file, the default can be overridden using the MaximumResponseHeadersLength property. /// </remarks> /// </devdoc> public static int DefaultMaximumResponseHeadersLength { get { return _defaultMaxResponseHeadersLength; } set { _defaultMaxResponseHeadersLength = value; } } // NOP public static int DefaultMaximumErrorResponseLength { get; set; } private static RequestCachePolicy? _defaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); private static bool _isDefaultCachePolicySet; public static new RequestCachePolicy? DefaultCachePolicy { get { return _defaultCachePolicy; } set { _isDefaultCachePolicySet = true; _defaultCachePolicy = value; } } public DateTime IfModifiedSince { get { return GetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince); } set { SetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince, value); } } /// <devdoc> /// <para> /// Gets or sets the value of the Date header. /// </para> /// </devdoc> public DateTime Date { get { return GetDateHeaderHelper(HttpKnownHeaderNames.Date); } set { SetDateHeaderHelper(HttpKnownHeaderNames.Date, value); } } public bool SendChunked { get { return (_booleans & Booleans.SendChunked) != 0; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } if (value) { _booleans |= Booleans.SendChunked; } else { _booleans &= ~Booleans.SendChunked; } } } public HttpContinueDelegate? ContinueDelegate { // Nop since the underlying API do not expose 100 continue. get { return _continueDelegate; } set { _continueDelegate = value; } } public ServicePoint ServicePoint => _servicePoint ??= ServicePointManager.FindServicePoint(Address, Proxy); public RemoteCertificateValidationCallback? ServerCertificateValidationCallback { get; set; } // // ClientCertificates - sets our certs for our reqest, // uses a hash of the collection to create a private connection // group, to prevent us from using the same Connection as // non-Client Authenticated requests. // public X509CertificateCollection ClientCertificates { get => _clientCertificates ??= new X509CertificateCollection(); set { ArgumentNullException.ThrowIfNull(value); _clientCertificates = value; } } // HTTP Version /// <devdoc> /// <para> /// Gets and sets /// the HTTP protocol version used in this request. /// </para> /// </devdoc> public Version ProtocolVersion { get { return IsVersionHttp10 ? HttpVersion.Version10 : HttpVersion.Version11; } set { if (value.Equals(HttpVersion.Version11)) { IsVersionHttp10 = false; } else if (value.Equals(HttpVersion.Version10)) { IsVersionHttp10 = true; } else { throw new ArgumentException(SR.net_wrongversion, nameof(value)); } } } public int ReadWriteTimeout { get { return _readWriteTimeout; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } _readWriteTimeout = value; } } public virtual CookieContainer? CookieContainer { get { return _cookieContainer; } set { _cookieContainer = value; } } public override ICredentials? Credentials { get { return _credentials; } set { _credentials = value; } } public virtual bool HaveResponse { get { return (_sendRequestTask != null) && (_sendRequestTask.IsCompletedSuccessfully); } } public override WebHeaderCollection Headers { get { return _webHeaderCollection; } set { // We can't change headers after they've already been sent. if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } WebHeaderCollection webHeaders = value; WebHeaderCollection newWebHeaders = new WebHeaderCollection(); // Copy And Validate - // Handle the case where their object tries to change // name, value pairs after they call set, so therefore, // we need to clone their headers. foreach (string headerName in webHeaders.AllKeys) { newWebHeaders[headerName] = webHeaders[headerName]; } _webHeaderCollection = newWebHeaders; } } public override string Method { get { return _originVerb; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_badmethod, nameof(value)); } if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value)) { throw new ArgumentException(SR.net_badmethod, nameof(value)); } _originVerb = value; } } public override Uri RequestUri { get { return _requestUri; } } public virtual bool SupportsCookieContainer { get { return true; } } public override bool UseDefaultCredentials { get { return (_credentials == CredentialCache.DefaultCredentials); } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } // Match Desktop behavior. Changing this property will also // change the .Credentials property as well. _credentials = value ? CredentialCache.DefaultCredentials : null; } } public override IWebProxy? Proxy { get { return _proxy; } set { // We can't change the proxy while the request is already fired. if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } _proxy = value; } } public override void Abort() { if (Interlocked.Exchange(ref _abortCalled, 1) != 0) { return; } // .NET Desktop behavior requires us to invoke outstanding callbacks // before returning if used in either the BeginGetRequestStream or // BeginGetResponse methods. // // If we can transition the task to the canceled state, then we invoke // the callback. If we can't transition the task, it is because it is // already in the terminal state and the callback has already been invoked // via the async task continuation. if (_responseOperation != null) { if (_responseOperation.TrySetCanceled() && _responseCallback != null) { _responseCallback(_responseOperation.Task); } // Cancel the underlying send operation. Debug.Assert(_sendRequestCts != null); _sendRequestCts.Cancel(); } else if (_requestStreamOperation != null) { if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null) { _requestStreamCallback(_requestStreamOperation.Task); } } } // HTTP version of the request private bool IsVersionHttp10 { get { return (_booleans & Booleans.IsVersionHttp10) != 0; } set { if (value) { _booleans |= Booleans.IsVersionHttp10; } else { _booleans &= ~Booleans.IsVersionHttp10; } } } public override WebResponse GetResponse() { try { _sendRequestCts = new CancellationTokenSource(); return SendRequest(async: false).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } } public override Stream GetRequestStream() { return InternalGetRequestStream().Result; } private Task<Stream> InternalGetRequestStream() { CheckAbort(); // Match Desktop behavior: prevent someone from getting a request stream // if the protocol verb/method doesn't support it. Note that this is not // entirely compliant RFC2616 for the aforementioned compatibility reasons. if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) || string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) || string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase)) { throw new ProtocolViolationException(SR.net_nouploadonget); } if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } _requestStream = new RequestStream(); return Task.FromResult((Stream)_requestStream); } public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext? context) { context = null; return EndGetRequestStream(asyncResult); } public Stream GetRequestStream(out TransportContext? context) { context = null; return GetRequestStream(); } public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state) { CheckAbort(); if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0) { throw new InvalidOperationException(SR.net_repcall); } _requestStreamCallback = callback; _requestStreamOperation = InternalGetRequestStream().ToApm(callback, state); return _requestStreamOperation.Task; } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { CheckAbort(); if (asyncResult == null || !(asyncResult is Task<Stream>)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream")); } Stream stream; try { stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } return stream; } private async Task<WebResponse> SendRequest(bool async) { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri); bool disposeRequired = false; HttpClient? client = null; try { client = GetCachedOrCreateHttpClient(async, out disposeRequired); if (_requestStream != null) { ArraySegment<byte> bytes = _requestStream.GetBuffer(); request.Content = new ByteArrayContent(bytes.Array!, bytes.Offset, bytes.Count); } if (_hostUri != null) { request.Headers.Host = Host; } AddCacheControlHeaders(request); // Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and // HttpRequestMessage.Content.Headers. foreach (string headerName in _webHeaderCollection) { // The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers // collection and the request content headers collection for all well-known header names. And custom headers // are only allowed in the request headers collection and not in the request content headers collection. if (IsWellKnownContentHeader(headerName)) { if (request.Content == null) { // Create empty content so that we can send the entity-body header. request.Content = new ByteArrayContent(Array.Empty<byte>()); } request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName!]); } else { request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName!]); } } request.Headers.TransferEncodingChunked = SendChunked; if (KeepAlive) { request.Headers.Connection.Add(HttpKnownHeaderNames.KeepAlive); } else { request.Headers.ConnectionClose = true; } request.Version = ProtocolVersion; _sendRequestTask = async ? client.SendAsync(request, _allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead, _sendRequestCts!.Token) : Task.FromResult(client.Send(request, _allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead, _sendRequestCts!.Token)); HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false); HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer); int maxSuccessStatusCode = AllowAutoRedirect ? 299 : 399; if ((int)response.StatusCode > maxSuccessStatusCode || (int)response.StatusCode < 200) { throw new WebException( SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription), null, WebExceptionStatus.ProtocolError, response); } return response; } finally { if (disposeRequired) { client?.Dispose(); } } } private void AddCacheControlHeaders(HttpRequestMessage request) { RequestCachePolicy? policy = GetApplicableCachePolicy(); if (policy != null && policy.Level != RequestCacheLevel.BypassCache) { CacheControlHeaderValue? cacheControl = null; HttpHeaderValueCollection<NameValueHeaderValue> pragmaHeaders = request.Headers.Pragma; if (policy is HttpRequestCachePolicy httpRequestCachePolicy) { switch (httpRequestCachePolicy.Level) { case HttpRequestCacheLevel.NoCacheNoStore: cacheControl = new CacheControlHeaderValue { NoCache = true, NoStore = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case HttpRequestCacheLevel.Reload: cacheControl = new CacheControlHeaderValue { NoCache = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case HttpRequestCacheLevel.CacheOnly: throw new WebException(SR.CacheEntryNotFound, WebExceptionStatus.CacheEntryNotFound); case HttpRequestCacheLevel.CacheOrNextCacheOnly: cacheControl = new CacheControlHeaderValue { OnlyIfCached = true }; break; case HttpRequestCacheLevel.Default: cacheControl = new CacheControlHeaderValue(); if (httpRequestCachePolicy.MinFresh > TimeSpan.Zero) { cacheControl.MinFresh = httpRequestCachePolicy.MinFresh; } if (httpRequestCachePolicy.MaxAge != TimeSpan.MaxValue) { cacheControl.MaxAge = httpRequestCachePolicy.MaxAge; } if (httpRequestCachePolicy.MaxStale > TimeSpan.Zero) { cacheControl.MaxStale = true; cacheControl.MaxStaleLimit = httpRequestCachePolicy.MaxStale; } break; case HttpRequestCacheLevel.Refresh: cacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.Zero }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; } } else { switch (policy.Level) { case RequestCacheLevel.NoCacheNoStore: cacheControl = new CacheControlHeaderValue { NoCache = true, NoStore = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case RequestCacheLevel.Reload: cacheControl = new CacheControlHeaderValue { NoCache = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case RequestCacheLevel.CacheOnly: throw new WebException(SR.CacheEntryNotFound, WebExceptionStatus.CacheEntryNotFound); } } if (cacheControl != null) { request.Headers.CacheControl = cacheControl; } } } private RequestCachePolicy? GetApplicableCachePolicy() { if (CachePolicy != null) { return CachePolicy; } else if (_isDefaultCachePolicySet && DefaultCachePolicy != null) { return DefaultCachePolicy; } else { return WebRequest.DefaultCachePolicy; } } public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state) { CheckAbort(); if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0) { throw new InvalidOperationException(SR.net_repcall); } _sendRequestCts = new CancellationTokenSource(); _responseCallback = callback; _responseOperation = SendRequest(async: true).ToApm(callback, state); return _responseOperation.Task; } public override WebResponse EndGetResponse(IAsyncResult asyncResult) { CheckAbort(); if (asyncResult == null || !(asyncResult is Task<WebResponse>)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse")); } WebResponse response; try { response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } return response; } /// <devdoc> /// <para> /// Adds a range header to the request for a specified range. /// </para> /// </devdoc> public void AddRange(int from, int to) { AddRange("bytes", (long)from, (long)to); } /// <devdoc> /// <para> /// Adds a range header to the request for a specified range. /// </para> /// </devdoc> public void AddRange(long from, long to) { AddRange("bytes", from, to); } /// <devdoc> /// <para> /// Adds a range header to a request for a specific /// range from the beginning or end /// of the requested data. /// To add the range from the end pass negative value /// To add the range from the some offset to the end pass positive value /// </para> /// </devdoc> public void AddRange(int range) { AddRange("bytes", (long)range); } /// <devdoc> /// <para> /// Adds a range header to a request for a specific /// range from the beginning or end /// of the requested data. /// To add the range from the end pass negative value /// To add the range from the some offset to the end pass positive value /// </para> /// </devdoc> public void AddRange(long range) { AddRange("bytes", range); } public void AddRange(string rangeSpecifier, int from, int to) { AddRange(rangeSpecifier, (long)from, (long)to); } public void AddRange(string rangeSpecifier!!, long from, long to) { if ((from < 0) || (to < 0)) { throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall); } if (from > to) { throw new ArgumentOutOfRangeException(nameof(from), SR.net_fromto); } if (!HttpValidationHelpers.IsValidToken(rangeSpecifier)) { throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier)); } if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo))) { throw new InvalidOperationException(SR.net_rangetype); } } public void AddRange(string rangeSpecifier, int range) { AddRange(rangeSpecifier, (long)range); } public void AddRange(string rangeSpecifier!!, long range) { if (!HttpValidationHelpers.IsValidToken(rangeSpecifier)) { throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier)); } if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null)) { throw new InvalidOperationException(SR.net_rangetype); } } private bool AddRange(string rangeSpecifier, string from, string? to) { string? curRange = _webHeaderCollection[HttpKnownHeaderNames.Range]; if ((curRange == null) || (curRange.Length == 0)) { curRange = rangeSpecifier + "="; } else { if (!string.Equals(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase)) { return false; } curRange = string.Empty; } curRange += from.ToString(); if (to != null) { curRange += "-" + to; } _webHeaderCollection[HttpKnownHeaderNames.Range] = curRange; return true; } private bool RequestSubmitted { get { return _sendRequestTask != null; } } private void CheckAbort() { if (Volatile.Read(ref _abortCalled) == 1) { throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled); } } private static readonly string[] s_wellKnownContentHeaders = { HttpKnownHeaderNames.ContentDisposition, HttpKnownHeaderNames.ContentEncoding, HttpKnownHeaderNames.ContentLanguage, HttpKnownHeaderNames.ContentLength, HttpKnownHeaderNames.ContentLocation, HttpKnownHeaderNames.ContentMD5, HttpKnownHeaderNames.ContentRange, HttpKnownHeaderNames.ContentType, HttpKnownHeaderNames.Expires, HttpKnownHeaderNames.LastModified }; private bool IsWellKnownContentHeader(string header) { foreach (string contentHeaderName in s_wellKnownContentHeaders) { if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } private DateTime GetDateHeaderHelper(string headerName) { string? headerValue = _webHeaderCollection[headerName]; if (headerValue == null) { return DateTime.MinValue; // MinValue means header is not present } if (HttpDateParser.TryParse(headerValue, out DateTimeOffset dateTimeOffset)) { return dateTimeOffset.LocalDateTime; } else { throw new ProtocolViolationException(SR.net_baddate); } } private void SetDateHeaderHelper(string headerName, DateTime dateTime) { if (dateTime == DateTime.MinValue) SetSpecialHeaders(headerName, null); // remove header else SetSpecialHeaders(headerName, HttpDateParser.DateToString(dateTime.ToUniversalTime())); } private bool TryGetHostUri(string hostName, [NotNullWhen(true)] out Uri? hostUri) { string s = Address.Scheme + "://" + hostName + Address.PathAndQuery; return Uri.TryCreate(s, UriKind.Absolute, out hostUri); } private HttpClient GetCachedOrCreateHttpClient(bool async, out bool disposeRequired) { var parameters = new HttpClientParameters(this, async); if (parameters.AreParametersAcceptableForCaching()) { disposeRequired = false; if (s_cachedHttpClient == null) { lock (s_syncRoot) { if (s_cachedHttpClient == null) { s_cachedHttpClientParameters = parameters; s_cachedHttpClient = CreateHttpClient(parameters, null); return s_cachedHttpClient; } } } if (s_cachedHttpClientParameters!.Matches(parameters)) { return s_cachedHttpClient; } } disposeRequired = true; return CreateHttpClient(parameters, this); } private static HttpClient CreateHttpClient(HttpClientParameters parameters, HttpWebRequest? request) { HttpClient? client = null; try { var handler = new SocketsHttpHandler(); client = new HttpClient(handler); handler.AutomaticDecompression = parameters.AutomaticDecompression; handler.Credentials = parameters.Credentials; handler.AllowAutoRedirect = parameters.AllowAutoRedirect; handler.MaxAutomaticRedirections = parameters.MaximumAutomaticRedirections; handler.MaxResponseHeadersLength = parameters.MaximumResponseHeadersLength; handler.PreAuthenticate = parameters.PreAuthenticate; client.Timeout = parameters.Timeout; if (parameters.CookieContainer != null) { handler.CookieContainer = parameters.CookieContainer; Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true. } else { handler.UseCookies = false; } Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true. Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null. // HttpClientHandler default is to use a proxy which is the system proxy. // This is indicated by the properties 'UseProxy == true' and 'Proxy == null'. // // However, HttpWebRequest doesn't have a separate 'UseProxy' property. Instead, // the default of the 'Proxy' property is a non-null IWebProxy object which is the // system default proxy object. If the 'Proxy' property were actually null, then // that means don't use any proxy. // // So, we need to map the desired HttpWebRequest proxy settings to equivalent // HttpClientHandler settings. if (parameters.Proxy == null) { handler.UseProxy = false; } else if (!object.ReferenceEquals(parameters.Proxy, WebRequest.GetSystemWebProxy())) { handler.Proxy = parameters.Proxy; } else { // Since this HttpWebRequest is using the default system proxy, we need to // pass any proxy credentials that the developer might have set via the // WebRequest.DefaultWebProxy.Credentials property. handler.DefaultProxyCredentials = parameters.Proxy.Credentials; } if (parameters.ClientCertificates != null) { handler.SslOptions.ClientCertificates = new X509CertificateCollection(parameters.ClientCertificates); } // Set relevant properties from ServicePointManager handler.SslOptions.EnabledSslProtocols = (SslProtocols)parameters.SslProtocols; handler.SslOptions.CertificateRevocationCheckMode = parameters.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck; RemoteCertificateValidationCallback? rcvc = parameters.ServerCertificateValidationCallback; if (rcvc != null) { handler.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) => rcvc(request!, cert, chain, errors); } // Set up a ConnectCallback so that we can control Socket-specific settings, like ReadWriteTimeout => socket.Send/ReceiveTimeout. handler.ConnectCallback = async (context, cancellationToken) => { var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); try { socket.NoDelay = true; if (parameters.Async) { await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false); } else { using (cancellationToken.UnsafeRegister(s => ((Socket)s!).Dispose(), socket)) { socket.Connect(context.DnsEndPoint); } // Throw in case cancellation caused the socket to be disposed after the Connect completed cancellationToken.ThrowIfCancellationRequested(); } if (parameters.ReadWriteTimeout > 0) // default is 5 minutes, so this is generally going to be true { socket.SendTimeout = socket.ReceiveTimeout = parameters.ReadWriteTimeout; } } catch { socket.Dispose(); throw; } return new NetworkStream(socket, ownsSocket: true); }; return client; } catch { client?.Dispose(); throw; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net.Cache; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Net.Sockets; using System.Runtime.Serialization; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net { public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders); public class HttpWebRequest : WebRequest, ISerializable { private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop. private const int DefaultReadWriteTimeout = 5 * 60 * 1000; // 5 minutes private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection(); private readonly Uri _requestUri = null!; private string _originVerb = HttpMethod.Get.Method; // We allow getting and setting this (to preserve app-compat). But we don't do anything with it // as the underlying System.Net.Http API doesn't support it. private int _continueTimeout = DefaultContinueTimeout; private bool _allowReadStreamBuffering; private CookieContainer? _cookieContainer; private ICredentials? _credentials; private IWebProxy? _proxy = WebRequest.DefaultWebProxy; private Task<HttpResponseMessage>? _sendRequestTask; private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private int _beginGetRequestStreamCalled; private int _beginGetResponseCalled; private int _endGetRequestStreamCalled; private int _endGetResponseCalled; private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maximumResponseHeadersLen = _defaultMaxResponseHeadersLength; private ServicePoint? _servicePoint; private int _timeout = WebRequest.DefaultTimeoutMilliseconds; private int _readWriteTimeout = DefaultReadWriteTimeout; private HttpContinueDelegate? _continueDelegate; // stores the user provided Host header as Uri. If the user specified a default port explicitly we'll lose // that information when converting the host string to a Uri. _HostHasPort will store that information. private bool _hostHasPort; private Uri? _hostUri; private RequestStream? _requestStream; private TaskCompletionSource<Stream>? _requestStreamOperation; private TaskCompletionSource<WebResponse>? _responseOperation; private AsyncCallback? _requestStreamCallback; private AsyncCallback? _responseCallback; private int _abortCalled; private CancellationTokenSource? _sendRequestCts; private X509CertificateCollection? _clientCertificates; private Booleans _booleans = Booleans.Default; private bool _pipelined = true; private bool _preAuthenticate; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private static readonly object s_syncRoot = new object(); private static volatile HttpClient? s_cachedHttpClient; private static HttpClientParameters? s_cachedHttpClientParameters; //these should be safe. [Flags] private enum Booleans : uint { AllowAutoRedirect = 0x00000001, AllowWriteStreamBuffering = 0x00000002, ExpectContinue = 0x00000004, ProxySet = 0x00000010, UnsafeAuthenticatedConnectionSharing = 0x00000040, IsVersionHttp10 = 0x00000080, SendChunked = 0x00000100, EnableDecompression = 0x00000200, IsTunnelRequest = 0x00000400, IsWebSocketRequest = 0x00000800, Default = AllowAutoRedirect | AllowWriteStreamBuffering | ExpectContinue } private sealed class HttpClientParameters { public readonly bool Async; public readonly DecompressionMethods AutomaticDecompression; public readonly bool AllowAutoRedirect; public readonly int MaximumAutomaticRedirections; public readonly int MaximumResponseHeadersLength; public readonly bool PreAuthenticate; public readonly int ReadWriteTimeout; public readonly TimeSpan Timeout; public readonly SecurityProtocolType SslProtocols; public readonly bool CheckCertificateRevocationList; public readonly ICredentials? Credentials; public readonly IWebProxy? Proxy; public readonly RemoteCertificateValidationCallback? ServerCertificateValidationCallback; public readonly X509CertificateCollection? ClientCertificates; public readonly CookieContainer? CookieContainer; public HttpClientParameters(HttpWebRequest webRequest, bool async) { Async = async; AutomaticDecompression = webRequest.AutomaticDecompression; AllowAutoRedirect = webRequest.AllowAutoRedirect; MaximumAutomaticRedirections = webRequest.MaximumAutomaticRedirections; MaximumResponseHeadersLength = webRequest.MaximumResponseHeadersLength; PreAuthenticate = webRequest.PreAuthenticate; ReadWriteTimeout = webRequest.ReadWriteTimeout; Timeout = webRequest.Timeout == Threading.Timeout.Infinite ? Threading.Timeout.InfiniteTimeSpan : TimeSpan.FromMilliseconds(webRequest.Timeout); SslProtocols = ServicePointManager.SecurityProtocol; CheckCertificateRevocationList = ServicePointManager.CheckCertificateRevocationList; Credentials = webRequest._credentials; Proxy = webRequest._proxy; ServerCertificateValidationCallback = webRequest.ServerCertificateValidationCallback ?? ServicePointManager.ServerCertificateValidationCallback; ClientCertificates = webRequest._clientCertificates; CookieContainer = webRequest._cookieContainer; } public bool Matches(HttpClientParameters requestParameters) { return Async == requestParameters.Async && AutomaticDecompression == requestParameters.AutomaticDecompression && AllowAutoRedirect == requestParameters.AllowAutoRedirect && MaximumAutomaticRedirections == requestParameters.MaximumAutomaticRedirections && MaximumResponseHeadersLength == requestParameters.MaximumResponseHeadersLength && PreAuthenticate == requestParameters.PreAuthenticate && ReadWriteTimeout == requestParameters.ReadWriteTimeout && Timeout == requestParameters.Timeout && SslProtocols == requestParameters.SslProtocols && CheckCertificateRevocationList == requestParameters.CheckCertificateRevocationList && ReferenceEquals(Credentials, requestParameters.Credentials) && ReferenceEquals(Proxy, requestParameters.Proxy) && ReferenceEquals(ServerCertificateValidationCallback, requestParameters.ServerCertificateValidationCallback) && ReferenceEquals(ClientCertificates, requestParameters.ClientCertificates) && ReferenceEquals(CookieContainer, requestParameters.CookieContainer); } public bool AreParametersAcceptableForCaching() { return Credentials == null && ReferenceEquals(Proxy, DefaultWebProxy) && ServerCertificateValidationCallback == null && ClientCertificates == null && CookieContainer == null; } } private const string ContinueHeader = "100-continue"; private const string ChunkedHeader = "chunked"; [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { throw new PlatformNotSupportedException(); } [Obsolete("Serialization has been deprecated for HttpWebRequest.")] void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(); } [Obsolete("Serialization has been deprecated for HttpWebRequest.")] protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(); } internal HttpWebRequest(Uri uri) { _requestUri = uri; } private void SetSpecialHeaders(string HeaderName, string? value) { _webHeaderCollection.Remove(HeaderName); if (!string.IsNullOrEmpty(value)) { _webHeaderCollection[HeaderName] = value; } } public string? Accept { get { return _webHeaderCollection[HttpKnownHeaderNames.Accept]; } set { SetSpecialHeaders(HttpKnownHeaderNames.Accept, value); } } public virtual bool AllowReadStreamBuffering { get { return _allowReadStreamBuffering; } set { _allowReadStreamBuffering = value; } } public int MaximumResponseHeadersLength { get => _maximumResponseHeadersLen; set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_toosmall); } _maximumResponseHeadersLen = value; } } public int MaximumAutomaticRedirections { get { return _maximumAllowedRedirections; } set { if (value <= 0) { throw new ArgumentException(SR.net_toosmall, nameof(value)); } _maximumAllowedRedirections = value; } } public override string? ContentType { get { return _webHeaderCollection[HttpKnownHeaderNames.ContentType]; } set { SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value); } } public int ContinueTimeout { get { return _continueTimeout; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if ((value < 0) && (value != System.Threading.Timeout.Infinite)) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } _continueTimeout = value; } } public override int Timeout { get { return _timeout; } set { if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } _timeout = value; } } public override long ContentLength { get { long value; long.TryParse(_webHeaderCollection[HttpKnownHeaderNames.ContentLength], out value); return value; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall); } SetSpecialHeaders(HttpKnownHeaderNames.ContentLength, value.ToString()); } } public Uri Address { get { return _requestUri; } } public string? UserAgent { get { return _webHeaderCollection[HttpKnownHeaderNames.UserAgent]; } set { SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value); } } public string Host { get { Uri hostUri = _hostUri ?? Address; return (_hostUri == null || !_hostHasPort) && Address.IsDefaultPort ? hostUri.Host : hostUri.Host + ":" + hostUri.Port; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } ArgumentNullException.ThrowIfNull(value); Uri? hostUri; if ((value.Contains('/')) || (!TryGetHostUri(value, out hostUri))) { throw new ArgumentException(SR.net_invalid_host, nameof(value)); } _hostUri = hostUri; // Determine if the user provided string contains a port if (!_hostUri.IsDefaultPort) { _hostHasPort = true; } else if (!value.Contains(':')) { _hostHasPort = false; } else { int endOfIPv6Address = value.IndexOf(']'); _hostHasPort = endOfIPv6Address == -1 || value.LastIndexOf(':') > endOfIPv6Address; } } } public bool Pipelined { get { return _pipelined; } set { _pipelined = value; } } /// <devdoc> /// <para> /// Gets or sets the value of the Referer header. /// </para> /// </devdoc> public string? Referer { get { return _webHeaderCollection[HttpKnownHeaderNames.Referer]; } set { SetSpecialHeaders(HttpKnownHeaderNames.Referer, value); } } /// <devdoc> /// <para>Sets the media type header</para> /// </devdoc> public string? MediaType { get; set; } /// <devdoc> /// <para> /// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out. /// </para> /// </devdoc> public string? TransferEncoding { get { return _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding]; } set { bool fChunked; // // on blank string, remove current header // if (string.IsNullOrWhiteSpace(value)) { // // if the value is blank, then remove the header // _webHeaderCollection.Remove(HttpKnownHeaderNames.TransferEncoding); return; } // // if not check if the user is trying to set chunked: // fChunked = (value.IndexOf(ChunkedHeader, StringComparison.OrdinalIgnoreCase) != -1); // // prevent them from adding chunked, or from adding an Encoding without // turning on chunked, the reason is due to the HTTP Spec which prevents // additional encoding types from being used without chunked // if (fChunked) { throw new ArgumentException(SR.net_nochunked, nameof(value)); } else if (!SendChunked) { throw new InvalidOperationException(SR.net_needchunked); } else { string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value); _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding] = checkedValue; } } } public bool KeepAlive { get; set; } = true; public bool UnsafeAuthenticatedConnectionSharing { get { return (_booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != 0; } set { if (value) { _booleans |= Booleans.UnsafeAuthenticatedConnectionSharing; } else { _booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing; } } } public DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } _automaticDecompression = value; } } public virtual bool AllowWriteStreamBuffering { get { return (_booleans & Booleans.AllowWriteStreamBuffering) != 0; } set { if (value) { _booleans |= Booleans.AllowWriteStreamBuffering; } else { _booleans &= ~Booleans.AllowWriteStreamBuffering; } } } /// <devdoc> /// <para> /// Enables or disables automatically following redirection responses. /// </para> /// </devdoc> public virtual bool AllowAutoRedirect { get { return (_booleans & Booleans.AllowAutoRedirect) != 0; } set { if (value) { _booleans |= Booleans.AllowAutoRedirect; } else { _booleans &= ~Booleans.AllowAutoRedirect; } } } public override string? ConnectionGroupName { get; set; } public override bool PreAuthenticate { get { return _preAuthenticate; } set { _preAuthenticate = value; } } public string? Connection { get { return _webHeaderCollection[HttpKnownHeaderNames.Connection]; } set { bool fKeepAlive; bool fClose; // // on blank string, remove current header // if (string.IsNullOrWhiteSpace(value)) { _webHeaderCollection.Remove(HttpKnownHeaderNames.Connection); return; } fKeepAlive = (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1); fClose = (value.IndexOf("close", StringComparison.OrdinalIgnoreCase) != -1); // // Prevent keep-alive and close from being added // if (fKeepAlive || fClose) { throw new ArgumentException(SR.net_connarg, nameof(value)); } else { string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value); _webHeaderCollection[HttpKnownHeaderNames.Connection] = checkedValue; } } } /* Accessor: Expect The property that controls the Expect header Input: string Expect, null clears the Expect except for 100-continue value Returns: The value of the Expect on get. */ public string? Expect { get { return _webHeaderCollection[HttpKnownHeaderNames.Expect]; } set { // only remove everything other than 100-cont bool fContinue100; // // on blank string, remove current header // if (string.IsNullOrWhiteSpace(value)) { _webHeaderCollection.Remove(HttpKnownHeaderNames.Expect); return; } // // Prevent 100-continues from being added // fContinue100 = (value.IndexOf(ContinueHeader, StringComparison.OrdinalIgnoreCase) != -1); if (fContinue100) { throw new ArgumentException(SR.net_no100, nameof(value)); } else { string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value); _webHeaderCollection[HttpKnownHeaderNames.Expect] = checkedValue; } } } /// <devdoc> /// <para> /// Gets or sets the default for the MaximumResponseHeadersLength property. /// </para> /// <remarks> /// This value can be set in the config file, the default can be overridden using the MaximumResponseHeadersLength property. /// </remarks> /// </devdoc> public static int DefaultMaximumResponseHeadersLength { get { return _defaultMaxResponseHeadersLength; } set { _defaultMaxResponseHeadersLength = value; } } // NOP public static int DefaultMaximumErrorResponseLength { get; set; } private static RequestCachePolicy? _defaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); private static bool _isDefaultCachePolicySet; public static new RequestCachePolicy? DefaultCachePolicy { get { return _defaultCachePolicy; } set { _isDefaultCachePolicySet = true; _defaultCachePolicy = value; } } public DateTime IfModifiedSince { get { return GetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince); } set { SetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince, value); } } /// <devdoc> /// <para> /// Gets or sets the value of the Date header. /// </para> /// </devdoc> public DateTime Date { get { return GetDateHeaderHelper(HttpKnownHeaderNames.Date); } set { SetDateHeaderHelper(HttpKnownHeaderNames.Date, value); } } public bool SendChunked { get { return (_booleans & Booleans.SendChunked) != 0; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } if (value) { _booleans |= Booleans.SendChunked; } else { _booleans &= ~Booleans.SendChunked; } } } public HttpContinueDelegate? ContinueDelegate { // Nop since the underlying API do not expose 100 continue. get { return _continueDelegate; } set { _continueDelegate = value; } } public ServicePoint ServicePoint => _servicePoint ??= ServicePointManager.FindServicePoint(Address, Proxy); public RemoteCertificateValidationCallback? ServerCertificateValidationCallback { get; set; } // // ClientCertificates - sets our certs for our reqest, // uses a hash of the collection to create a private connection // group, to prevent us from using the same Connection as // non-Client Authenticated requests. // public X509CertificateCollection ClientCertificates { get => _clientCertificates ??= new X509CertificateCollection(); set { ArgumentNullException.ThrowIfNull(value); _clientCertificates = value; } } // HTTP Version /// <devdoc> /// <para> /// Gets and sets /// the HTTP protocol version used in this request. /// </para> /// </devdoc> public Version ProtocolVersion { get { return IsVersionHttp10 ? HttpVersion.Version10 : HttpVersion.Version11; } set { if (value.Equals(HttpVersion.Version11)) { IsVersionHttp10 = false; } else if (value.Equals(HttpVersion.Version10)) { IsVersionHttp10 = true; } else { throw new ArgumentException(SR.net_wrongversion, nameof(value)); } } } public int ReadWriteTimeout { get { return _readWriteTimeout; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } _readWriteTimeout = value; } } public virtual CookieContainer? CookieContainer { get { return _cookieContainer; } set { _cookieContainer = value; } } public override ICredentials? Credentials { get { return _credentials; } set { _credentials = value; } } public virtual bool HaveResponse { get { return (_sendRequestTask != null) && (_sendRequestTask.IsCompletedSuccessfully); } } public override WebHeaderCollection Headers { get { return _webHeaderCollection; } set { // We can't change headers after they've already been sent. if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } WebHeaderCollection webHeaders = value; WebHeaderCollection newWebHeaders = new WebHeaderCollection(); // Copy And Validate - // Handle the case where their object tries to change // name, value pairs after they call set, so therefore, // we need to clone their headers. foreach (string headerName in webHeaders.AllKeys) { newWebHeaders[headerName] = webHeaders[headerName]; } _webHeaderCollection = newWebHeaders; } } public override string Method { get { return _originVerb; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_badmethod, nameof(value)); } if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value)) { throw new ArgumentException(SR.net_badmethod, nameof(value)); } _originVerb = value; } } public override Uri RequestUri { get { return _requestUri; } } public virtual bool SupportsCookieContainer { get { return true; } } public override bool UseDefaultCredentials { get { return (_credentials == CredentialCache.DefaultCredentials); } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } // Match Desktop behavior. Changing this property will also // change the .Credentials property as well. _credentials = value ? CredentialCache.DefaultCredentials : null; } } public override IWebProxy? Proxy { get { return _proxy; } set { // We can't change the proxy while the request is already fired. if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } _proxy = value; } } public override void Abort() { if (Interlocked.Exchange(ref _abortCalled, 1) != 0) { return; } // .NET Desktop behavior requires us to invoke outstanding callbacks // before returning if used in either the BeginGetRequestStream or // BeginGetResponse methods. // // If we can transition the task to the canceled state, then we invoke // the callback. If we can't transition the task, it is because it is // already in the terminal state and the callback has already been invoked // via the async task continuation. if (_responseOperation != null) { if (_responseOperation.TrySetCanceled() && _responseCallback != null) { _responseCallback(_responseOperation.Task); } // Cancel the underlying send operation. Debug.Assert(_sendRequestCts != null); _sendRequestCts.Cancel(); } else if (_requestStreamOperation != null) { if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null) { _requestStreamCallback(_requestStreamOperation.Task); } } } // HTTP version of the request private bool IsVersionHttp10 { get { return (_booleans & Booleans.IsVersionHttp10) != 0; } set { if (value) { _booleans |= Booleans.IsVersionHttp10; } else { _booleans &= ~Booleans.IsVersionHttp10; } } } public override WebResponse GetResponse() { try { _sendRequestCts = new CancellationTokenSource(); return SendRequest(async: false).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } } public override Stream GetRequestStream() { return InternalGetRequestStream().Result; } private Task<Stream> InternalGetRequestStream() { CheckAbort(); // Match Desktop behavior: prevent someone from getting a request stream // if the protocol verb/method doesn't support it. Note that this is not // entirely compliant RFC2616 for the aforementioned compatibility reasons. if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) || string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) || string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase)) { throw new ProtocolViolationException(SR.net_nouploadonget); } if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } _requestStream = new RequestStream(); return Task.FromResult((Stream)_requestStream); } public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext? context) { context = null; return EndGetRequestStream(asyncResult); } public Stream GetRequestStream(out TransportContext? context) { context = null; return GetRequestStream(); } public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, object? state) { CheckAbort(); if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0) { throw new InvalidOperationException(SR.net_repcall); } _requestStreamCallback = callback; _requestStreamOperation = InternalGetRequestStream().ToApm(callback, state); return _requestStreamOperation.Task; } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { CheckAbort(); if (asyncResult == null || !(asyncResult is Task<Stream>)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream")); } Stream stream; try { stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } return stream; } private async Task<WebResponse> SendRequest(bool async) { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri); bool disposeRequired = false; HttpClient? client = null; try { client = GetCachedOrCreateHttpClient(async, out disposeRequired); if (_requestStream != null) { ArraySegment<byte> bytes = _requestStream.GetBuffer(); request.Content = new ByteArrayContent(bytes.Array!, bytes.Offset, bytes.Count); } if (_hostUri != null) { request.Headers.Host = Host; } AddCacheControlHeaders(request); // Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and // HttpRequestMessage.Content.Headers. foreach (string headerName in _webHeaderCollection) { // The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers // collection and the request content headers collection for all well-known header names. And custom headers // are only allowed in the request headers collection and not in the request content headers collection. if (IsWellKnownContentHeader(headerName)) { if (request.Content == null) { // Create empty content so that we can send the entity-body header. request.Content = new ByteArrayContent(Array.Empty<byte>()); } request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName!]); } else { request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName!]); } } request.Headers.TransferEncodingChunked = SendChunked; if (KeepAlive) { request.Headers.Connection.Add(HttpKnownHeaderNames.KeepAlive); } else { request.Headers.ConnectionClose = true; } request.Version = ProtocolVersion; _sendRequestTask = async ? client.SendAsync(request, _allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead, _sendRequestCts!.Token) : Task.FromResult(client.Send(request, _allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead, _sendRequestCts!.Token)); HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false); HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer); int maxSuccessStatusCode = AllowAutoRedirect ? 299 : 399; if ((int)response.StatusCode > maxSuccessStatusCode || (int)response.StatusCode < 200) { throw new WebException( SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription), null, WebExceptionStatus.ProtocolError, response); } return response; } finally { if (disposeRequired) { client?.Dispose(); } } } private void AddCacheControlHeaders(HttpRequestMessage request) { RequestCachePolicy? policy = GetApplicableCachePolicy(); if (policy != null && policy.Level != RequestCacheLevel.BypassCache) { CacheControlHeaderValue? cacheControl = null; HttpHeaderValueCollection<NameValueHeaderValue> pragmaHeaders = request.Headers.Pragma; if (policy is HttpRequestCachePolicy httpRequestCachePolicy) { switch (httpRequestCachePolicy.Level) { case HttpRequestCacheLevel.NoCacheNoStore: cacheControl = new CacheControlHeaderValue { NoCache = true, NoStore = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case HttpRequestCacheLevel.Reload: cacheControl = new CacheControlHeaderValue { NoCache = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case HttpRequestCacheLevel.CacheOnly: throw new WebException(SR.CacheEntryNotFound, WebExceptionStatus.CacheEntryNotFound); case HttpRequestCacheLevel.CacheOrNextCacheOnly: cacheControl = new CacheControlHeaderValue { OnlyIfCached = true }; break; case HttpRequestCacheLevel.Default: cacheControl = new CacheControlHeaderValue(); if (httpRequestCachePolicy.MinFresh > TimeSpan.Zero) { cacheControl.MinFresh = httpRequestCachePolicy.MinFresh; } if (httpRequestCachePolicy.MaxAge != TimeSpan.MaxValue) { cacheControl.MaxAge = httpRequestCachePolicy.MaxAge; } if (httpRequestCachePolicy.MaxStale > TimeSpan.Zero) { cacheControl.MaxStale = true; cacheControl.MaxStaleLimit = httpRequestCachePolicy.MaxStale; } break; case HttpRequestCacheLevel.Refresh: cacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.Zero }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; } } else { switch (policy.Level) { case RequestCacheLevel.NoCacheNoStore: cacheControl = new CacheControlHeaderValue { NoCache = true, NoStore = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case RequestCacheLevel.Reload: cacheControl = new CacheControlHeaderValue { NoCache = true }; pragmaHeaders.Add(new NameValueHeaderValue("no-cache")); break; case RequestCacheLevel.CacheOnly: throw new WebException(SR.CacheEntryNotFound, WebExceptionStatus.CacheEntryNotFound); } } if (cacheControl != null) { request.Headers.CacheControl = cacheControl; } } } private RequestCachePolicy? GetApplicableCachePolicy() { if (CachePolicy != null) { return CachePolicy; } else if (_isDefaultCachePolicySet && DefaultCachePolicy != null) { return DefaultCachePolicy; } else { return WebRequest.DefaultCachePolicy; } } public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state) { CheckAbort(); if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0) { throw new InvalidOperationException(SR.net_repcall); } _sendRequestCts = new CancellationTokenSource(); _responseCallback = callback; _responseOperation = SendRequest(async: true).ToApm(callback, state); return _responseOperation.Task; } public override WebResponse EndGetResponse(IAsyncResult asyncResult) { CheckAbort(); if (asyncResult == null || !(asyncResult is Task<WebResponse>)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse")); } WebResponse response; try { response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } return response; } /// <devdoc> /// <para> /// Adds a range header to the request for a specified range. /// </para> /// </devdoc> public void AddRange(int from, int to) { AddRange("bytes", (long)from, (long)to); } /// <devdoc> /// <para> /// Adds a range header to the request for a specified range. /// </para> /// </devdoc> public void AddRange(long from, long to) { AddRange("bytes", from, to); } /// <devdoc> /// <para> /// Adds a range header to a request for a specific /// range from the beginning or end /// of the requested data. /// To add the range from the end pass negative value /// To add the range from the some offset to the end pass positive value /// </para> /// </devdoc> public void AddRange(int range) { AddRange("bytes", (long)range); } /// <devdoc> /// <para> /// Adds a range header to a request for a specific /// range from the beginning or end /// of the requested data. /// To add the range from the end pass negative value /// To add the range from the some offset to the end pass positive value /// </para> /// </devdoc> public void AddRange(long range) { AddRange("bytes", range); } public void AddRange(string rangeSpecifier, int from, int to) { AddRange(rangeSpecifier, (long)from, (long)to); } public void AddRange(string rangeSpecifier!!, long from, long to) { if ((from < 0) || (to < 0)) { throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall); } if (from > to) { throw new ArgumentOutOfRangeException(nameof(from), SR.net_fromto); } if (!HttpValidationHelpers.IsValidToken(rangeSpecifier)) { throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier)); } if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo))) { throw new InvalidOperationException(SR.net_rangetype); } } public void AddRange(string rangeSpecifier, int range) { AddRange(rangeSpecifier, (long)range); } public void AddRange(string rangeSpecifier!!, long range) { if (!HttpValidationHelpers.IsValidToken(rangeSpecifier)) { throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier)); } if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null)) { throw new InvalidOperationException(SR.net_rangetype); } } private bool AddRange(string rangeSpecifier, string from, string? to) { string? curRange = _webHeaderCollection[HttpKnownHeaderNames.Range]; if ((curRange == null) || (curRange.Length == 0)) { curRange = rangeSpecifier + "="; } else { if (!string.Equals(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase)) { return false; } curRange = string.Empty; } curRange += from.ToString(); if (to != null) { curRange += "-" + to; } _webHeaderCollection[HttpKnownHeaderNames.Range] = curRange; return true; } private bool RequestSubmitted { get { return _sendRequestTask != null; } } private void CheckAbort() { if (Volatile.Read(ref _abortCalled) == 1) { throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled); } } private static readonly string[] s_wellKnownContentHeaders = { HttpKnownHeaderNames.ContentDisposition, HttpKnownHeaderNames.ContentEncoding, HttpKnownHeaderNames.ContentLanguage, HttpKnownHeaderNames.ContentLength, HttpKnownHeaderNames.ContentLocation, HttpKnownHeaderNames.ContentMD5, HttpKnownHeaderNames.ContentRange, HttpKnownHeaderNames.ContentType, HttpKnownHeaderNames.Expires, HttpKnownHeaderNames.LastModified }; private bool IsWellKnownContentHeader(string header) { foreach (string contentHeaderName in s_wellKnownContentHeaders) { if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } private DateTime GetDateHeaderHelper(string headerName) { string? headerValue = _webHeaderCollection[headerName]; if (headerValue == null) { return DateTime.MinValue; // MinValue means header is not present } if (HttpDateParser.TryParse(headerValue, out DateTimeOffset dateTimeOffset)) { return dateTimeOffset.LocalDateTime; } else { throw new ProtocolViolationException(SR.net_baddate); } } private void SetDateHeaderHelper(string headerName, DateTime dateTime) { if (dateTime == DateTime.MinValue) SetSpecialHeaders(headerName, null); // remove header else SetSpecialHeaders(headerName, HttpDateParser.DateToString(dateTime.ToUniversalTime())); } private bool TryGetHostUri(string hostName, [NotNullWhen(true)] out Uri? hostUri) { string s = Address.Scheme + "://" + hostName + Address.PathAndQuery; return Uri.TryCreate(s, UriKind.Absolute, out hostUri); } private HttpClient GetCachedOrCreateHttpClient(bool async, out bool disposeRequired) { var parameters = new HttpClientParameters(this, async); if (parameters.AreParametersAcceptableForCaching()) { disposeRequired = false; if (s_cachedHttpClient == null) { lock (s_syncRoot) { if (s_cachedHttpClient == null) { s_cachedHttpClientParameters = parameters; s_cachedHttpClient = CreateHttpClient(parameters, null); return s_cachedHttpClient; } } } if (s_cachedHttpClientParameters!.Matches(parameters)) { return s_cachedHttpClient; } } disposeRequired = true; return CreateHttpClient(parameters, this); } private static HttpClient CreateHttpClient(HttpClientParameters parameters, HttpWebRequest? request) { HttpClient? client = null; try { var handler = new SocketsHttpHandler(); client = new HttpClient(handler); handler.AutomaticDecompression = parameters.AutomaticDecompression; handler.Credentials = parameters.Credentials; handler.AllowAutoRedirect = parameters.AllowAutoRedirect; handler.MaxAutomaticRedirections = parameters.MaximumAutomaticRedirections; handler.MaxResponseHeadersLength = parameters.MaximumResponseHeadersLength; handler.PreAuthenticate = parameters.PreAuthenticate; client.Timeout = parameters.Timeout; if (parameters.CookieContainer != null) { handler.CookieContainer = parameters.CookieContainer; Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true. } else { handler.UseCookies = false; } Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true. Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null. // HttpClientHandler default is to use a proxy which is the system proxy. // This is indicated by the properties 'UseProxy == true' and 'Proxy == null'. // // However, HttpWebRequest doesn't have a separate 'UseProxy' property. Instead, // the default of the 'Proxy' property is a non-null IWebProxy object which is the // system default proxy object. If the 'Proxy' property were actually null, then // that means don't use any proxy. // // So, we need to map the desired HttpWebRequest proxy settings to equivalent // HttpClientHandler settings. if (parameters.Proxy == null) { handler.UseProxy = false; } else if (!object.ReferenceEquals(parameters.Proxy, WebRequest.GetSystemWebProxy())) { handler.Proxy = parameters.Proxy; } else { // Since this HttpWebRequest is using the default system proxy, we need to // pass any proxy credentials that the developer might have set via the // WebRequest.DefaultWebProxy.Credentials property. handler.DefaultProxyCredentials = parameters.Proxy.Credentials; } if (parameters.ClientCertificates != null) { handler.SslOptions.ClientCertificates = new X509CertificateCollection(parameters.ClientCertificates); } // Set relevant properties from ServicePointManager handler.SslOptions.EnabledSslProtocols = (SslProtocols)parameters.SslProtocols; handler.SslOptions.CertificateRevocationCheckMode = parameters.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck; RemoteCertificateValidationCallback? rcvc = parameters.ServerCertificateValidationCallback; if (rcvc != null) { handler.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) => rcvc(request!, cert, chain, errors); } // Set up a ConnectCallback so that we can control Socket-specific settings, like ReadWriteTimeout => socket.Send/ReceiveTimeout. handler.ConnectCallback = async (context, cancellationToken) => { var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); try { socket.NoDelay = true; if (parameters.Async) { await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false); } else { using (cancellationToken.UnsafeRegister(s => ((Socket)s!).Dispose(), socket)) { socket.Connect(context.DnsEndPoint); } // Throw in case cancellation caused the socket to be disposed after the Connect completed cancellationToken.ThrowIfCancellationRequested(); } if (parameters.ReadWriteTimeout > 0) // default is 5 minutes, so this is generally going to be true { socket.SendTimeout = socket.ReceiveTimeout = parameters.ReadWriteTimeout; } } catch { socket.Dispose(); throw; } return new NetworkStream(socket, ownsSocket: true); }; return client; } catch { client?.Dispose(); throw; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/Loader/classloader/v1/Beta1/Layout/Matrix/cs/L-1-9-3.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="L-1-9-3.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="L-1-9-3D.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="L-1-9-3.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="L-1-9-3D.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/coreclr/pal/src/libunwind/src/hppa/Greg_states_iterate.c
/* libunwind - a platform-independent unwind library Copyright (c) 2002-2003 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> Modified for x86_64 by Max Asbock <[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 "unwind_i.h" int unw_reg_states_iterate (unw_cursor_t *cursor, unw_reg_states_callback cb, void *token) { struct cursor *c = (struct cursor *) cursor; return dwarf_reg_states_iterate (&c->dwarf, cb, token); }
/* libunwind - a platform-independent unwind library Copyright (c) 2002-2003 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> Modified for x86_64 by Max Asbock <[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 "unwind_i.h" int unw_reg_states_iterate (unw_cursor_t *cursor, unw_reg_states_callback cb, void *token) { struct cursor *c = (struct cursor *) cursor; return dwarf_reg_states_iterate (&c->dwarf, cb, token); }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b423755/Desktop/b423755.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="b423755.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="b423755.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Net.Mail/tests/Functional/ContentDispositionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using Xunit; namespace System.Net.Mime.Tests { public class ContentDispositionTest { private const string ValidDateGmt = "Sun, 17 May 2009 15:34:07 GMT"; private const string ValidDateGmtOffset = "Sun, 17 May 2009 15:34:07 +0000"; private const string ValidDateUnspecified = "Sun, 17 May 2009 15:34:07 -0000"; private const string ValidDateTimeLocal = "Sun, 17 May 2009 15:34:07 -0800"; private const string ValidDateTimeNotLocal = "Sun, 17 May 2009 15:34:07 -0200"; private const string InvalidDate = "Sun, 32 Say 2009 25:15:15 7m-gte"; private static readonly TimeSpan s_localTimeOffset = TimeZoneInfo.Local.GetUtcOffset(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local)); [Fact] public static void DefaultCtor_ExpectedDefaultPropertyValues() { var cd = new ContentDisposition(); Assert.Equal(DateTime.MinValue, cd.CreationDate); Assert.Equal("attachment", cd.DispositionType); Assert.Null(cd.FileName); Assert.False(cd.Inline); Assert.Equal(DateTime.MinValue, cd.ModificationDate); Assert.Empty(cd.Parameters); Assert.Equal(DateTime.MinValue, cd.ReadDate); Assert.Equal(-1, cd.Size); Assert.Equal("attachment", cd.ToString()); } [Fact] public void ConstructorWithOtherPropertyValues_ShouldSetAppropriately() { var cd = new ContentDisposition("attachment;creation-date=\"" + ValidDateTimeLocal + "\";read-date=\"" + ValidDateTimeLocal + "\";modification-date=\"" + ValidDateTimeLocal + "\";filename=\"=?utf-8?B?dGVzdC50eHTnkIY=?=\";size=200"); Assert.Equal("attachment", cd.DispositionType); Assert.False(cd.Inline); Assert.Equal(200, cd.Size); Assert.Equal("=?utf-8?B?dGVzdC50eHTnkIY=?=", cd.FileName); cd.FileName = "test.txt\x7406"; Assert.Equal("test.txt\x7406", cd.FileName); } [Theory] [InlineData(typeof(ArgumentNullException), null)] [InlineData(typeof(FormatException), "inline; creation-date=\"" + InvalidDate + "\";")] [InlineData(typeof(FormatException), "inline; size=\"notANumber\"")] public static void Ctor_InvalidThrows(Type exceptionType, string contentDisposition) { Assert.Throws(exceptionType, () => new ContentDisposition(contentDisposition)); } [Theory] [InlineData(typeof(ArgumentNullException), null)] [InlineData(typeof(ArgumentException), "")] public static void DispositionType_SetValue_InvalidThrows(Type exceptionType, string contentDisposition) { Assert.Throws(exceptionType, () => new ContentDisposition().DispositionType = contentDisposition); } [Fact] public static void Filename_Roundtrip() { var cd = new ContentDisposition(); Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); cd.FileName = "hello"; Assert.Equal("hello", cd.FileName); Assert.Equal(1, cd.Parameters.Count); Assert.Equal("hello", cd.Parameters["filename"]); Assert.Equal("attachment; filename=hello", cd.ToString()); cd.FileName = "world"; Assert.Equal("world", cd.FileName); Assert.Equal(1, cd.Parameters.Count); Assert.Equal("world", cd.Parameters["filename"]); Assert.Equal("attachment; filename=world", cd.ToString()); cd.FileName = null; Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); cd.FileName = string.Empty; Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); } [Fact] public static void Inline_Roundtrip() { var cd = new ContentDisposition(); Assert.False(cd.Inline); cd.Inline = true; Assert.True(cd.Inline); cd.Inline = false; Assert.False(cd.Inline); Assert.Empty(cd.Parameters); } [Fact] public static void Dates_RoundtripWithoutImpactingOtherDates() { var cd = new ContentDisposition(); Assert.Equal(DateTime.MinValue, cd.CreationDate); Assert.Equal(DateTime.MinValue, cd.ModificationDate); Assert.Equal(DateTime.MinValue, cd.ReadDate); Assert.Empty(cd.Parameters); DateTime dt1 = DateTime.Now; cd.CreationDate = dt1; Assert.Equal(1, cd.Parameters.Count); DateTime dt2 = DateTime.Now; cd.ModificationDate = dt2; Assert.Equal(2, cd.Parameters.Count); DateTime dt3 = DateTime.Now; cd.ReadDate = dt3; Assert.Equal(3, cd.Parameters.Count); Assert.Equal(dt1, cd.CreationDate); Assert.Equal(dt2, cd.ModificationDate); Assert.Equal(dt3, cd.ReadDate); Assert.Equal(3, cd.Parameters.Count); } [Fact] public void SetAndResetDateViaParameters_ShouldWorkCorrectly() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateUnspecified; Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind); Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]); cd.Parameters["creation-date"] = ValidDateTimeLocal; Assert.Equal(ValidDateTimeLocal, cd.Parameters["creation-date"]); Assert.Equal(ValidDateTimeLocal, cd.Parameters["Creation-Date"]); } [Fact] public static void DispositionType_Roundtrip() { var cd = new ContentDisposition(); Assert.Equal("attachment", cd.DispositionType); Assert.Empty(cd.Parameters); cd.DispositionType = "hello"; Assert.Equal("hello", cd.DispositionType); cd.DispositionType = "world"; Assert.Equal("world", cd.DispositionType); Assert.Equal(0, cd.Parameters.Count); } [Fact] public static void Size_Roundtrip() { var cd = new ContentDisposition(); Assert.Equal(-1, cd.Size); Assert.Empty(cd.Parameters); cd.Size = 42; Assert.Equal(42, cd.Size); Assert.Equal(1, cd.Parameters.Count); } [Fact] public static void ConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse() { ContentDisposition contentDisposition = new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\""); var contentDisposition2 = new ContentDisposition(); contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]); contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]); Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate); Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate); } [Fact] public static void UseDifferentCultureAndConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse() { ContentDisposition contentDisposition = new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\""); CultureInfo origCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("zh-cn"); try { ContentDisposition contentDisposition2 = new ContentDisposition(); contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]); contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]); Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate); Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate); } finally { CultureInfo.CurrentCulture = origCulture; } } [Fact] public void SetDateViaConstructor_ShouldPersistToPropertyAndPersistToParametersCollection() { string disposition = "inline; creation-date=\"" + ValidDateGmt + "\";"; string dispositionValue = "inline; creation-date=\"" + ValidDateGmtOffset + "\""; var cd = new ContentDisposition(disposition); Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); Assert.Equal("inline", cd.DispositionType); Assert.Equal(dispositionValue, cd.ToString()); } [Fact] public static void SetDateViaProperty_ShouldPersistToProprtyAndParametersCollection_AndRespectKindProperty() { DateTime date = new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Unspecified); var cd = new ContentDisposition("inline"); cd.CreationDate = date; Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]); Assert.Equal(date, cd.CreationDate); } [Fact] public static void GetViaDateTimeProperty_WithUniversalTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateGmt; Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); } [Fact] public void GetViaDateTimeProperty_WithLocalTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateTimeLocal; Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind); Assert.Equal(ValidDateTimeLocal, cd.Parameters["creation-date"]); } [Fact] public void GetViaDateTimeProperty_WithOtherTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateUnspecified; Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind); } [Fact] public void GetViaDateTimeProperty_WithNonLocalTimeZone_ShouldWorkCorrectly() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateTimeNotLocal; DateTime result = cd.CreationDate; Assert.Equal(ValidDateTimeNotLocal, cd.Parameters["creation-date"]); Assert.Equal(DateTimeKind.Local, result.Kind); // be sure that the local offset isn't the same as the offset we're testing // so that this comparison will be valid if (s_localTimeOffset != new TimeSpan(-2, 0, 0)) { Assert.NotEqual(ValidDateTimeNotLocal, result.ToString("ddd, dd MMM yyyy H:mm:ss")); } } [Fact] public void SetCreateDateViaParameters_WithInvalidDate_ShouldThrow() { var cd = new ContentDisposition("inline"); Assert.Throws<FormatException>(() => { cd.Parameters["creation-date"] = InvalidDate; //string date = cd.Parameters["creation-date"]; }); } [Fact] public void GetCustomerParameterThatIsNotSet_ShouldReturnNull() { var cd = new ContentDisposition("inline"); Assert.Null(cd.Parameters["doesnotexist"]); Assert.Equal("inline", cd.DispositionType); Assert.True(cd.Inline); } [Fact] public void SetDispositionViaConstructor_ShouldSetCorrectly_AndRespectCustomValues() { var cd = new ContentDisposition("inline; creation-date=\"" + ValidDateGmtOffset + "\"; X-Test=\"value\""); Assert.Equal("inline", cd.DispositionType); Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); } [Fact] public void CultureSensitiveSetDateViaProperty_ShouldPersistToProprtyAndParametersCollectionAndRespectKindProperty() { CultureInfo origCulture = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo("zh"); var cd = new ContentDisposition("inline"); var date = new DateTime(2011, 6, 8, 15, 34, 07, DateTimeKind.Unspecified); cd.CreationDate = date; Assert.Equal("Wed, 08 Jun 2011 15:34:07 -0000", cd.Parameters["creation-date"]); Assert.Equal(date, cd.CreationDate); Assert.Equal("inline; creation-date=\"Wed, 08 Jun 2011 15:34:07 -0000\"", cd.ToString()); } finally { CultureInfo.CurrentCulture = origCulture; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using Xunit; namespace System.Net.Mime.Tests { public class ContentDispositionTest { private const string ValidDateGmt = "Sun, 17 May 2009 15:34:07 GMT"; private const string ValidDateGmtOffset = "Sun, 17 May 2009 15:34:07 +0000"; private const string ValidDateUnspecified = "Sun, 17 May 2009 15:34:07 -0000"; private const string ValidDateTimeLocal = "Sun, 17 May 2009 15:34:07 -0800"; private const string ValidDateTimeNotLocal = "Sun, 17 May 2009 15:34:07 -0200"; private const string InvalidDate = "Sun, 32 Say 2009 25:15:15 7m-gte"; private static readonly TimeSpan s_localTimeOffset = TimeZoneInfo.Local.GetUtcOffset(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local)); [Fact] public static void DefaultCtor_ExpectedDefaultPropertyValues() { var cd = new ContentDisposition(); Assert.Equal(DateTime.MinValue, cd.CreationDate); Assert.Equal("attachment", cd.DispositionType); Assert.Null(cd.FileName); Assert.False(cd.Inline); Assert.Equal(DateTime.MinValue, cd.ModificationDate); Assert.Empty(cd.Parameters); Assert.Equal(DateTime.MinValue, cd.ReadDate); Assert.Equal(-1, cd.Size); Assert.Equal("attachment", cd.ToString()); } [Fact] public void ConstructorWithOtherPropertyValues_ShouldSetAppropriately() { var cd = new ContentDisposition("attachment;creation-date=\"" + ValidDateTimeLocal + "\";read-date=\"" + ValidDateTimeLocal + "\";modification-date=\"" + ValidDateTimeLocal + "\";filename=\"=?utf-8?B?dGVzdC50eHTnkIY=?=\";size=200"); Assert.Equal("attachment", cd.DispositionType); Assert.False(cd.Inline); Assert.Equal(200, cd.Size); Assert.Equal("=?utf-8?B?dGVzdC50eHTnkIY=?=", cd.FileName); cd.FileName = "test.txt\x7406"; Assert.Equal("test.txt\x7406", cd.FileName); } [Theory] [InlineData(typeof(ArgumentNullException), null)] [InlineData(typeof(FormatException), "inline; creation-date=\"" + InvalidDate + "\";")] [InlineData(typeof(FormatException), "inline; size=\"notANumber\"")] public static void Ctor_InvalidThrows(Type exceptionType, string contentDisposition) { Assert.Throws(exceptionType, () => new ContentDisposition(contentDisposition)); } [Theory] [InlineData(typeof(ArgumentNullException), null)] [InlineData(typeof(ArgumentException), "")] public static void DispositionType_SetValue_InvalidThrows(Type exceptionType, string contentDisposition) { Assert.Throws(exceptionType, () => new ContentDisposition().DispositionType = contentDisposition); } [Fact] public static void Filename_Roundtrip() { var cd = new ContentDisposition(); Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); cd.FileName = "hello"; Assert.Equal("hello", cd.FileName); Assert.Equal(1, cd.Parameters.Count); Assert.Equal("hello", cd.Parameters["filename"]); Assert.Equal("attachment; filename=hello", cd.ToString()); cd.FileName = "world"; Assert.Equal("world", cd.FileName); Assert.Equal(1, cd.Parameters.Count); Assert.Equal("world", cd.Parameters["filename"]); Assert.Equal("attachment; filename=world", cd.ToString()); cd.FileName = null; Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); cd.FileName = string.Empty; Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); } [Fact] public static void Inline_Roundtrip() { var cd = new ContentDisposition(); Assert.False(cd.Inline); cd.Inline = true; Assert.True(cd.Inline); cd.Inline = false; Assert.False(cd.Inline); Assert.Empty(cd.Parameters); } [Fact] public static void Dates_RoundtripWithoutImpactingOtherDates() { var cd = new ContentDisposition(); Assert.Equal(DateTime.MinValue, cd.CreationDate); Assert.Equal(DateTime.MinValue, cd.ModificationDate); Assert.Equal(DateTime.MinValue, cd.ReadDate); Assert.Empty(cd.Parameters); DateTime dt1 = DateTime.Now; cd.CreationDate = dt1; Assert.Equal(1, cd.Parameters.Count); DateTime dt2 = DateTime.Now; cd.ModificationDate = dt2; Assert.Equal(2, cd.Parameters.Count); DateTime dt3 = DateTime.Now; cd.ReadDate = dt3; Assert.Equal(3, cd.Parameters.Count); Assert.Equal(dt1, cd.CreationDate); Assert.Equal(dt2, cd.ModificationDate); Assert.Equal(dt3, cd.ReadDate); Assert.Equal(3, cd.Parameters.Count); } [Fact] public void SetAndResetDateViaParameters_ShouldWorkCorrectly() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateUnspecified; Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind); Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]); cd.Parameters["creation-date"] = ValidDateTimeLocal; Assert.Equal(ValidDateTimeLocal, cd.Parameters["creation-date"]); Assert.Equal(ValidDateTimeLocal, cd.Parameters["Creation-Date"]); } [Fact] public static void DispositionType_Roundtrip() { var cd = new ContentDisposition(); Assert.Equal("attachment", cd.DispositionType); Assert.Empty(cd.Parameters); cd.DispositionType = "hello"; Assert.Equal("hello", cd.DispositionType); cd.DispositionType = "world"; Assert.Equal("world", cd.DispositionType); Assert.Equal(0, cd.Parameters.Count); } [Fact] public static void Size_Roundtrip() { var cd = new ContentDisposition(); Assert.Equal(-1, cd.Size); Assert.Empty(cd.Parameters); cd.Size = 42; Assert.Equal(42, cd.Size); Assert.Equal(1, cd.Parameters.Count); } [Fact] public static void ConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse() { ContentDisposition contentDisposition = new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\""); var contentDisposition2 = new ContentDisposition(); contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]); contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]); Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate); Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate); } [Fact] public static void UseDifferentCultureAndConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse() { ContentDisposition contentDisposition = new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\""); CultureInfo origCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("zh-cn"); try { ContentDisposition contentDisposition2 = new ContentDisposition(); contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]); contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]); Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate); Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate); } finally { CultureInfo.CurrentCulture = origCulture; } } [Fact] public void SetDateViaConstructor_ShouldPersistToPropertyAndPersistToParametersCollection() { string disposition = "inline; creation-date=\"" + ValidDateGmt + "\";"; string dispositionValue = "inline; creation-date=\"" + ValidDateGmtOffset + "\""; var cd = new ContentDisposition(disposition); Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); Assert.Equal("inline", cd.DispositionType); Assert.Equal(dispositionValue, cd.ToString()); } [Fact] public static void SetDateViaProperty_ShouldPersistToProprtyAndParametersCollection_AndRespectKindProperty() { DateTime date = new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Unspecified); var cd = new ContentDisposition("inline"); cd.CreationDate = date; Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]); Assert.Equal(date, cd.CreationDate); } [Fact] public static void GetViaDateTimeProperty_WithUniversalTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateGmt; Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); } [Fact] public void GetViaDateTimeProperty_WithLocalTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateTimeLocal; Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind); Assert.Equal(ValidDateTimeLocal, cd.Parameters["creation-date"]); } [Fact] public void GetViaDateTimeProperty_WithOtherTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateUnspecified; Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind); } [Fact] public void GetViaDateTimeProperty_WithNonLocalTimeZone_ShouldWorkCorrectly() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateTimeNotLocal; DateTime result = cd.CreationDate; Assert.Equal(ValidDateTimeNotLocal, cd.Parameters["creation-date"]); Assert.Equal(DateTimeKind.Local, result.Kind); // be sure that the local offset isn't the same as the offset we're testing // so that this comparison will be valid if (s_localTimeOffset != new TimeSpan(-2, 0, 0)) { Assert.NotEqual(ValidDateTimeNotLocal, result.ToString("ddd, dd MMM yyyy H:mm:ss")); } } [Fact] public void SetCreateDateViaParameters_WithInvalidDate_ShouldThrow() { var cd = new ContentDisposition("inline"); Assert.Throws<FormatException>(() => { cd.Parameters["creation-date"] = InvalidDate; //string date = cd.Parameters["creation-date"]; }); } [Fact] public void GetCustomerParameterThatIsNotSet_ShouldReturnNull() { var cd = new ContentDisposition("inline"); Assert.Null(cd.Parameters["doesnotexist"]); Assert.Equal("inline", cd.DispositionType); Assert.True(cd.Inline); } [Fact] public void SetDispositionViaConstructor_ShouldSetCorrectly_AndRespectCustomValues() { var cd = new ContentDisposition("inline; creation-date=\"" + ValidDateGmtOffset + "\"; X-Test=\"value\""); Assert.Equal("inline", cd.DispositionType); Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); } [Fact] public void CultureSensitiveSetDateViaProperty_ShouldPersistToProprtyAndParametersCollectionAndRespectKindProperty() { CultureInfo origCulture = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo("zh"); var cd = new ContentDisposition("inline"); var date = new DateTime(2011, 6, 8, 15, 34, 07, DateTimeKind.Unspecified); cd.CreationDate = date; Assert.Equal("Wed, 08 Jun 2011 15:34:07 -0000", cd.Parameters["creation-date"]); Assert.Equal(date, cd.CreationDate); Assert.Equal("inline; creation-date=\"Wed, 08 Jun 2011 15:34:07 -0000\"", cd.ToString()); } finally { CultureInfo.CurrentCulture = origCulture; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Microsoft.Extensions.Hosting/Microsoft.Extensions.Hosting.sln
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{BCAE2699-A994-48FE-B9B0-5580D267BD2E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bcl.AsyncInterfaces", "..\Microsoft.Bcl.AsyncInterfaces\ref\Microsoft.Bcl.AsyncInterfaces.csproj", "{47ACDB6F-34CB-478D-9E43-F3662EE5838D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bcl.AsyncInterfaces", "..\Microsoft.Bcl.AsyncInterfaces\src\Microsoft.Bcl.AsyncInterfaces.csproj", "{C24E4188-27CB-4E00-A5F0-62AE23D536EE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Abstractions", "..\Microsoft.Extensions.Configuration.Abstractions\ref\Microsoft.Extensions.Configuration.Abstractions.csproj", "{EDAC3418-1D4E-4216-9371-0A36EA1E13FE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Abstractions", "..\Microsoft.Extensions.Configuration.Abstractions\src\Microsoft.Extensions.Configuration.Abstractions.csproj", "{020874FC-11A2-4FC7-8929-527462F8819A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Binder", "..\Microsoft.Extensions.Configuration.Binder\ref\Microsoft.Extensions.Configuration.Binder.csproj", "{670AB88D-85C9-4674-A652-C27488ED73F9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Binder", "..\Microsoft.Extensions.Configuration.Binder\src\Microsoft.Extensions.Configuration.Binder.csproj", "{3411D565-223A-44B5-864C-E30F826001B4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.CommandLine", "..\Microsoft.Extensions.Configuration.CommandLine\ref\Microsoft.Extensions.Configuration.CommandLine.csproj", "{4AB3E652-6709-4011-AC2F-C379A0415BAC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.CommandLine", "..\Microsoft.Extensions.Configuration.CommandLine\src\Microsoft.Extensions.Configuration.CommandLine.csproj", "{ECA6E734-3908-45B4-9DFA-FDDA49AD620D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.EnvironmentVariables", "..\Microsoft.Extensions.Configuration.EnvironmentVariables\ref\Microsoft.Extensions.Configuration.EnvironmentVariables.csproj", "{3D657A5A-C7DF-4817-864F-944755DCE6DF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.EnvironmentVariables", "..\Microsoft.Extensions.Configuration.EnvironmentVariables\src\Microsoft.Extensions.Configuration.EnvironmentVariables.csproj", "{0C041643-1217-466B-AF2E-1E44C7B117B1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.FileExtensions", "..\Microsoft.Extensions.Configuration.FileExtensions\ref\Microsoft.Extensions.Configuration.FileExtensions.csproj", "{BD938E1D-6FC8-4D46-B103-B4D35761CEA2}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.FileExtensions", "..\Microsoft.Extensions.Configuration.FileExtensions\src\Microsoft.Extensions.Configuration.FileExtensions.csproj", "{6DB8DE55-5419-48EA-B4CD-2880E00409FB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Json", "..\Microsoft.Extensions.Configuration.Json\ref\Microsoft.Extensions.Configuration.Json.csproj", "{1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Json", "..\Microsoft.Extensions.Configuration.Json\src\Microsoft.Extensions.Configuration.Json.csproj", "{0A738527-821F-4089-B64E-3C0F4714DC78}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.UserSecrets", "..\Microsoft.Extensions.Configuration.UserSecrets\ref\Microsoft.Extensions.Configuration.UserSecrets.csproj", "{37A36947-2652-4AFD-BCF8-AAFD4D4D2827}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.UserSecrets", "..\Microsoft.Extensions.Configuration.UserSecrets\src\Microsoft.Extensions.Configuration.UserSecrets.csproj", "{EA9E6747-867B-4312-94B3-624EEB1C7A7A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration", "..\Microsoft.Extensions.Configuration\ref\Microsoft.Extensions.Configuration.csproj", "{13BC7AAA-7831-4500-9D28-A93FA4CA3C74}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration", "..\Microsoft.Extensions.Configuration\src\Microsoft.Extensions.Configuration.csproj", "{EB889E78-AE59-4D41-AC29-8BC4D58BCE16}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection.Abstractions", "..\Microsoft.Extensions.DependencyInjection.Abstractions\ref\Microsoft.Extensions.DependencyInjection.Abstractions.csproj", "{135F551E-ACB8-4073-ABB5-A1FA558455DE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection.Abstractions", "..\Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj", "{0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection", "..\Microsoft.Extensions.DependencyInjection\ref\Microsoft.Extensions.DependencyInjection.csproj", "{5532E155-E423-4FFD-B009-80B4281D36BA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection", "..\Microsoft.Extensions.DependencyInjection\src\Microsoft.Extensions.DependencyInjection.csproj", "{6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Abstractions", "..\Microsoft.Extensions.FileProviders.Abstractions\ref\Microsoft.Extensions.FileProviders.Abstractions.csproj", "{24220AD7-03ED-427A-BFC8-114C475EAD0F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Abstractions", "..\Microsoft.Extensions.FileProviders.Abstractions\src\Microsoft.Extensions.FileProviders.Abstractions.csproj", "{0A021166-613C-430C-8460-50F1E0DF7AD8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Physical", "..\Microsoft.Extensions.FileProviders.Physical\ref\Microsoft.Extensions.FileProviders.Physical.csproj", "{376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Physical", "..\Microsoft.Extensions.FileProviders.Physical\src\Microsoft.Extensions.FileProviders.Physical.csproj", "{1E3D564C-A79E-4E28-8E13-626EE7780831}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileSystemGlobbing", "..\Microsoft.Extensions.FileSystemGlobbing\ref\Microsoft.Extensions.FileSystemGlobbing.csproj", "{E4157F2E-F11D-48C6-A146-B4D12D9211F7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileSystemGlobbing", "..\Microsoft.Extensions.FileSystemGlobbing\src\Microsoft.Extensions.FileSystemGlobbing.csproj", "{9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Abstractions", "..\Microsoft.Extensions.Hosting.Abstractions\ref\Microsoft.Extensions.Hosting.Abstractions.csproj", "{2F25C0DB-E010-4802-8030-C88E2D09D3B0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Abstractions", "..\Microsoft.Extensions.Hosting.Abstractions\src\Microsoft.Extensions.Hosting.Abstractions.csproj", "{973CE6DA-B55D-4E55-88D5-53BE69D44410}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting", "ref\Microsoft.Extensions.Hosting.csproj", "{0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting", "src\Microsoft.Extensions.Hosting.csproj", "{F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Functional.Tests", "tests\FunctionalTests\Microsoft.Extensions.Hosting.Functional.Tests.csproj", "{2A882DCC-96C1-4EDF-A7F0-B526EC81533F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.TestApp", "tests\TestApp\Microsoft.Extensions.Hosting.TestApp.csproj", "{495208B7-31BB-4802-A769-CEE4917BDF75}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Unit.Tests", "tests\UnitTests\Microsoft.Extensions.Hosting.Unit.Tests.csproj", "{33C3D8F0-297F-4471-92B0-F4E8717F10E3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators.Roslyn3.11", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn3.11.csproj", "{1B235247-6666-4B62-95A4-AC043626FDEA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators.Roslyn4.0", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn4.0.csproj", "{5F6EF6F2-A742-445B-9418-682188F61130}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Abstractions", "..\Microsoft.Extensions.Logging.Abstractions\ref\Microsoft.Extensions.Logging.Abstractions.csproj", "{42E1BF94-6FE0-4017-9702-55913BD95EDE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Abstractions", "..\Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj", "{8845E6FF-94B2-4994-A8F4-DF30844A2168}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Configuration", "..\Microsoft.Extensions.Logging.Configuration\ref\Microsoft.Extensions.Logging.Configuration.csproj", "{15AD68F8-6C58-41A3-99B3-558C42A6E7A5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Configuration", "..\Microsoft.Extensions.Logging.Configuration\src\Microsoft.Extensions.Logging.Configuration.csproj", "{99C8FB58-8718-4E76-AEFA-3C42F2F729B1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Console", "..\Microsoft.Extensions.Logging.Console\ref\Microsoft.Extensions.Logging.Console.csproj", "{28C9D427-83BA-46A6-BEF5-6994A07F2258}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Console", "..\Microsoft.Extensions.Logging.Console\src\Microsoft.Extensions.Logging.Console.csproj", "{F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Debug", "..\Microsoft.Extensions.Logging.Debug\ref\Microsoft.Extensions.Logging.Debug.csproj", "{098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Debug", "..\Microsoft.Extensions.Logging.Debug\src\Microsoft.Extensions.Logging.Debug.csproj", "{B729474D-0E96-4296-B317-450EE24F6B48}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventLog", "..\Microsoft.Extensions.Logging.EventLog\ref\Microsoft.Extensions.Logging.EventLog.csproj", "{9ADBD2EE-D390-490C-BBEA-F844FE6F371E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventLog", "..\Microsoft.Extensions.Logging.EventLog\src\Microsoft.Extensions.Logging.EventLog.csproj", "{2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventSource", "..\Microsoft.Extensions.Logging.EventSource\ref\Microsoft.Extensions.Logging.EventSource.csproj", "{465AE1C4-84DD-4864-916A-74D89DC3BBBC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventSource", "..\Microsoft.Extensions.Logging.EventSource\src\Microsoft.Extensions.Logging.EventSource.csproj", "{D466E363-F930-4D26-AE55-0256182961DD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging", "..\Microsoft.Extensions.Logging\ref\Microsoft.Extensions.Logging.csproj", "{D69326FC-CD05-4690-91C0-1537A80ACBFF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging", "..\Microsoft.Extensions.Logging\src\Microsoft.Extensions.Logging.csproj", "{518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options.ConfigurationExtensions", "..\Microsoft.Extensions.Options.ConfigurationExtensions\ref\Microsoft.Extensions.Options.ConfigurationExtensions.csproj", "{014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options.ConfigurationExtensions", "..\Microsoft.Extensions.Options.ConfigurationExtensions\src\Microsoft.Extensions.Options.ConfigurationExtensions.csproj", "{0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options", "..\Microsoft.Extensions.Options\ref\Microsoft.Extensions.Options.csproj", "{DD121F9F-3548-4247-8E10-FB584FC0827C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options", "..\Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj", "{25C5119A-AAFB-4C74-9E12-F747CA4D80E7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Primitives", "..\Microsoft.Extensions.Primitives\ref\Microsoft.Extensions.Primitives.csproj", "{45235656-E284-4682-BE70-9A284FD73243}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Primitives", "..\Microsoft.Extensions.Primitives\src\Microsoft.Extensions.Primitives.csproj", "{D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.DiagnosticSource", "..\System.Diagnostics.DiagnosticSource\ref\System.Diagnostics.DiagnosticSource.csproj", "{28726AEF-2732-4832-8930-074ACD9DC732}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.DiagnosticSource", "..\System.Diagnostics.DiagnosticSource\src\System.Diagnostics.DiagnosticSource.csproj", "{0BC9E4F4-5C34-4B90-80AB-2933992D99A6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.EventLog", "..\System.Diagnostics.EventLog\ref\System.Diagnostics.EventLog.csproj", "{34ECA788-A105-411B-AE8B-17B7CC1D703D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.EventLog.Messages", "..\System.Diagnostics.EventLog\src\Messages\System.Diagnostics.EventLog.Messages.csproj", "{A5DD36AF-F0AD-4616-AB91-BC63E89B2744}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.EventLog", "..\System.Diagnostics.EventLog\src\System.Diagnostics.EventLog.csproj", "{4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Drawing.Common", "..\System.Drawing.Common\ref\System.Drawing.Common.csproj", "{EB6CB1A4-1D66-49B8-9914-BA12B47C909F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{C00722C2-E56B-424F-9216-FA6A91788986}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{90DD4D77-E3DC-456E-A27F-F13DA6194481}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Permissions", "..\System.Security.Permissions\ref\System.Security.Permissions.csproj", "{FEC2349C-D18C-40B0-BA21-2111E383E972}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Encodings.Web", "..\System.Text.Encodings.Web\ref\System.Text.Encodings.Web.csproj", "{C595A27A-FA05-4BC8-9048-402338D7AF76}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Encodings.Web", "..\System.Text.Encodings.Web\src\System.Text.Encodings.Web.csproj", "{B41AA17B-5129-41CC-8EA4-250B80BABF87}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration.Roslyn3.11", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn3.11.csproj", "{0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration.Roslyn4.0", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn4.0.csproj", "{B69B7D59-6E7D-43FC-B83F-AA481B677B06}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json", "..\System.Text.Json\ref\System.Text.Json.csproj", "{1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json", "..\System.Text.Json\src\System.Text.Json.csproj", "{0813853E-8C78-429A-B01A-3FB2EF1898F8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Windows.Extensions", "..\System.Windows.Extensions\ref\System.Windows.Extensions.csproj", "{C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{E041754F-1A93-443A-9294-87DC1C30B471}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{59A29BF0-B76B-41F8-A733-E2A0847AB992}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{A9A8D649-4C09-4FD1-9837-EE7B9D902253}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Debug|Any CPU.Build.0 = Debug|Any CPU {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Release|Any CPU.ActiveCfg = Release|Any CPU {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Release|Any CPU.Build.0 = Release|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Debug|Any CPU.Build.0 = Debug|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Release|Any CPU.ActiveCfg = Release|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Release|Any CPU.Build.0 = Release|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Debug|Any CPU.Build.0 = Debug|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Release|Any CPU.ActiveCfg = Release|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Release|Any CPU.Build.0 = Release|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Release|Any CPU.Build.0 = Release|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Debug|Any CPU.Build.0 = Debug|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Release|Any CPU.ActiveCfg = Release|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Release|Any CPU.Build.0 = Release|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Release|Any CPU.Build.0 = Release|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Debug|Any CPU.Build.0 = Debug|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Release|Any CPU.ActiveCfg = Release|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Release|Any CPU.Build.0 = Release|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Debug|Any CPU.Build.0 = Debug|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Release|Any CPU.ActiveCfg = Release|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Release|Any CPU.Build.0 = Release|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Debug|Any CPU.Build.0 = Debug|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Release|Any CPU.ActiveCfg = Release|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Release|Any CPU.Build.0 = Release|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Debug|Any CPU.Build.0 = Debug|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Release|Any CPU.ActiveCfg = Release|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Release|Any CPU.Build.0 = Release|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Release|Any CPU.Build.0 = Release|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Debug|Any CPU.Build.0 = Debug|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Release|Any CPU.ActiveCfg = Release|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Release|Any CPU.Build.0 = Release|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Debug|Any CPU.Build.0 = Debug|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Release|Any CPU.ActiveCfg = Release|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Release|Any CPU.Build.0 = Release|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Debug|Any CPU.Build.0 = Debug|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Release|Any CPU.ActiveCfg = Release|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Release|Any CPU.Build.0 = Release|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Release|Any CPU.Build.0 = Release|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Debug|Any CPU.Build.0 = Debug|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Release|Any CPU.ActiveCfg = Release|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Release|Any CPU.Build.0 = Release|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Debug|Any CPU.Build.0 = Debug|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Release|Any CPU.ActiveCfg = Release|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Release|Any CPU.Build.0 = Release|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Debug|Any CPU.Build.0 = Debug|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Release|Any CPU.ActiveCfg = Release|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Release|Any CPU.Build.0 = Release|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Debug|Any CPU.Build.0 = Debug|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Release|Any CPU.ActiveCfg = Release|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Release|Any CPU.Build.0 = Release|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Debug|Any CPU.Build.0 = Debug|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Release|Any CPU.ActiveCfg = Release|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Release|Any CPU.Build.0 = Release|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Debug|Any CPU.Build.0 = Debug|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Release|Any CPU.ActiveCfg = Release|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Release|Any CPU.Build.0 = Release|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Debug|Any CPU.Build.0 = Debug|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Release|Any CPU.ActiveCfg = Release|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Release|Any CPU.Build.0 = Release|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Debug|Any CPU.Build.0 = Debug|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Release|Any CPU.ActiveCfg = Release|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Release|Any CPU.Build.0 = Release|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Debug|Any CPU.Build.0 = Debug|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Release|Any CPU.ActiveCfg = Release|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Release|Any CPU.Build.0 = Release|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Release|Any CPU.Build.0 = Release|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Debug|Any CPU.Build.0 = Debug|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Release|Any CPU.ActiveCfg = Release|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Release|Any CPU.Build.0 = Release|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Release|Any CPU.ActiveCfg = Release|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Release|Any CPU.Build.0 = Release|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Debug|Any CPU.Build.0 = Debug|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Release|Any CPU.ActiveCfg = Release|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Release|Any CPU.Build.0 = Release|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Debug|Any CPU.Build.0 = Debug|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Release|Any CPU.ActiveCfg = Release|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Release|Any CPU.Build.0 = Release|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Release|Any CPU.Build.0 = Release|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Debug|Any CPU.Build.0 = Debug|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Release|Any CPU.ActiveCfg = Release|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Release|Any CPU.Build.0 = Release|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Debug|Any CPU.Build.0 = Debug|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Release|Any CPU.ActiveCfg = Release|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Release|Any CPU.Build.0 = Release|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Release|Any CPU.Build.0 = Release|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Release|Any CPU.Build.0 = Release|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Debug|Any CPU.Build.0 = Debug|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Release|Any CPU.ActiveCfg = Release|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Release|Any CPU.Build.0 = Release|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Debug|Any CPU.Build.0 = Debug|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Release|Any CPU.ActiveCfg = Release|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Release|Any CPU.Build.0 = Release|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Debug|Any CPU.Build.0 = Debug|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Release|Any CPU.ActiveCfg = Release|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Release|Any CPU.Build.0 = Release|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Debug|Any CPU.Build.0 = Debug|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Release|Any CPU.ActiveCfg = Release|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Release|Any CPU.Build.0 = Release|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Debug|Any CPU.Build.0 = Debug|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Release|Any CPU.ActiveCfg = Release|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Release|Any CPU.Build.0 = Release|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Debug|Any CPU.Build.0 = Debug|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Release|Any CPU.ActiveCfg = Release|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Release|Any CPU.Build.0 = Release|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Release|Any CPU.Build.0 = Release|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Release|Any CPU.Build.0 = Release|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Debug|Any CPU.Build.0 = Debug|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Release|Any CPU.ActiveCfg = Release|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Release|Any CPU.Build.0 = Release|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Debug|Any CPU.Build.0 = Debug|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Release|Any CPU.ActiveCfg = Release|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Release|Any CPU.Build.0 = Release|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Debug|Any CPU.Build.0 = Debug|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Release|Any CPU.ActiveCfg = Release|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Release|Any CPU.Build.0 = Release|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Debug|Any CPU.Build.0 = Debug|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Release|Any CPU.ActiveCfg = Release|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Release|Any CPU.Build.0 = Release|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Debug|Any CPU.Build.0 = Debug|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Release|Any CPU.ActiveCfg = Release|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Release|Any CPU.Build.0 = Release|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Debug|Any CPU.Build.0 = Debug|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Release|Any CPU.ActiveCfg = Release|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Release|Any CPU.Build.0 = Release|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Debug|Any CPU.Build.0 = Debug|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Release|Any CPU.ActiveCfg = Release|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Release|Any CPU.Build.0 = Release|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Debug|Any CPU.Build.0 = Debug|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Release|Any CPU.Build.0 = Release|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Debug|Any CPU.Build.0 = Debug|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Release|Any CPU.ActiveCfg = Release|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Release|Any CPU.Build.0 = Release|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Debug|Any CPU.Build.0 = Debug|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Release|Any CPU.ActiveCfg = Release|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Release|Any CPU.Build.0 = Release|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Debug|Any CPU.Build.0 = Debug|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Release|Any CPU.ActiveCfg = Release|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Release|Any CPU.Build.0 = Release|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Debug|Any CPU.Build.0 = Debug|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Release|Any CPU.ActiveCfg = Release|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Release|Any CPU.Build.0 = Release|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Debug|Any CPU.Build.0 = Debug|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Release|Any CPU.ActiveCfg = Release|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Release|Any CPU.Build.0 = Release|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Release|Any CPU.Build.0 = Release|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Debug|Any CPU.Build.0 = Debug|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Release|Any CPU.ActiveCfg = Release|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Release|Any CPU.Build.0 = Release|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Debug|Any CPU.Build.0 = Debug|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Release|Any CPU.ActiveCfg = Release|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Release|Any CPU.Build.0 = Release|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Debug|Any CPU.Build.0 = Debug|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Release|Any CPU.ActiveCfg = Release|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Release|Any CPU.Build.0 = Release|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Release|Any CPU.Build.0 = Release|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Debug|Any CPU.Build.0 = Debug|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Release|Any CPU.ActiveCfg = Release|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Release|Any CPU.Build.0 = Release|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Debug|Any CPU.Build.0 = Debug|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Release|Any CPU.ActiveCfg = Release|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Release|Any CPU.Build.0 = Release|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Debug|Any CPU.Build.0 = Debug|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Release|Any CPU.ActiveCfg = Release|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Release|Any CPU.Build.0 = Release|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Debug|Any CPU.Build.0 = Debug|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Release|Any CPU.ActiveCfg = Release|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Release|Any CPU.Build.0 = Release|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Debug|Any CPU.Build.0 = Debug|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Release|Any CPU.ActiveCfg = Release|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Release|Any CPU.Build.0 = Release|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Debug|Any CPU.Build.0 = Debug|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Release|Any CPU.ActiveCfg = Release|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Release|Any CPU.Build.0 = Release|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Debug|Any CPU.Build.0 = Debug|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Release|Any CPU.ActiveCfg = Release|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Release|Any CPU.Build.0 = Release|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Debug|Any CPU.Build.0 = Debug|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Release|Any CPU.ActiveCfg = Release|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Release|Any CPU.Build.0 = Release|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Debug|Any CPU.Build.0 = Debug|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Release|Any CPU.ActiveCfg = Release|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Release|Any CPU.Build.0 = Release|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Release|Any CPU.Build.0 = Release|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Debug|Any CPU.Build.0 = Debug|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Release|Any CPU.ActiveCfg = Release|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Release|Any CPU.Build.0 = Release|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Release|Any CPU.ActiveCfg = Release|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Release|Any CPU.Build.0 = Release|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Release|Any CPU.Build.0 = Release|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Debug|Any CPU.Build.0 = Debug|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Release|Any CPU.ActiveCfg = Release|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {BCAE2699-A994-48FE-B9B0-5580D267BD2E} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {2A882DCC-96C1-4EDF-A7F0-B526EC81533F} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {495208B7-31BB-4802-A769-CEE4917BDF75} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {33C3D8F0-297F-4471-92B0-F4E8717F10E3} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {47ACDB6F-34CB-478D-9E43-F3662EE5838D} = {E041754F-1A93-443A-9294-87DC1C30B471} {EDAC3418-1D4E-4216-9371-0A36EA1E13FE} = {E041754F-1A93-443A-9294-87DC1C30B471} {670AB88D-85C9-4674-A652-C27488ED73F9} = {E041754F-1A93-443A-9294-87DC1C30B471} {4AB3E652-6709-4011-AC2F-C379A0415BAC} = {E041754F-1A93-443A-9294-87DC1C30B471} {3D657A5A-C7DF-4817-864F-944755DCE6DF} = {E041754F-1A93-443A-9294-87DC1C30B471} {BD938E1D-6FC8-4D46-B103-B4D35761CEA2} = {E041754F-1A93-443A-9294-87DC1C30B471} {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC} = {E041754F-1A93-443A-9294-87DC1C30B471} {37A36947-2652-4AFD-BCF8-AAFD4D4D2827} = {E041754F-1A93-443A-9294-87DC1C30B471} {13BC7AAA-7831-4500-9D28-A93FA4CA3C74} = {E041754F-1A93-443A-9294-87DC1C30B471} {135F551E-ACB8-4073-ABB5-A1FA558455DE} = {E041754F-1A93-443A-9294-87DC1C30B471} {5532E155-E423-4FFD-B009-80B4281D36BA} = {E041754F-1A93-443A-9294-87DC1C30B471} {24220AD7-03ED-427A-BFC8-114C475EAD0F} = {E041754F-1A93-443A-9294-87DC1C30B471} {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F} = {E041754F-1A93-443A-9294-87DC1C30B471} {E4157F2E-F11D-48C6-A146-B4D12D9211F7} = {E041754F-1A93-443A-9294-87DC1C30B471} {2F25C0DB-E010-4802-8030-C88E2D09D3B0} = {E041754F-1A93-443A-9294-87DC1C30B471} {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84} = {E041754F-1A93-443A-9294-87DC1C30B471} {42E1BF94-6FE0-4017-9702-55913BD95EDE} = {E041754F-1A93-443A-9294-87DC1C30B471} {15AD68F8-6C58-41A3-99B3-558C42A6E7A5} = {E041754F-1A93-443A-9294-87DC1C30B471} {28C9D427-83BA-46A6-BEF5-6994A07F2258} = {E041754F-1A93-443A-9294-87DC1C30B471} {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B} = {E041754F-1A93-443A-9294-87DC1C30B471} {9ADBD2EE-D390-490C-BBEA-F844FE6F371E} = {E041754F-1A93-443A-9294-87DC1C30B471} {465AE1C4-84DD-4864-916A-74D89DC3BBBC} = {E041754F-1A93-443A-9294-87DC1C30B471} {D69326FC-CD05-4690-91C0-1537A80ACBFF} = {E041754F-1A93-443A-9294-87DC1C30B471} {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E} = {E041754F-1A93-443A-9294-87DC1C30B471} {DD121F9F-3548-4247-8E10-FB584FC0827C} = {E041754F-1A93-443A-9294-87DC1C30B471} {45235656-E284-4682-BE70-9A284FD73243} = {E041754F-1A93-443A-9294-87DC1C30B471} {28726AEF-2732-4832-8930-074ACD9DC732} = {E041754F-1A93-443A-9294-87DC1C30B471} {34ECA788-A105-411B-AE8B-17B7CC1D703D} = {E041754F-1A93-443A-9294-87DC1C30B471} {EB6CB1A4-1D66-49B8-9914-BA12B47C909F} = {E041754F-1A93-443A-9294-87DC1C30B471} {FEC2349C-D18C-40B0-BA21-2111E383E972} = {E041754F-1A93-443A-9294-87DC1C30B471} {C595A27A-FA05-4BC8-9048-402338D7AF76} = {E041754F-1A93-443A-9294-87DC1C30B471} {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952} = {E041754F-1A93-443A-9294-87DC1C30B471} {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519} = {E041754F-1A93-443A-9294-87DC1C30B471} {C24E4188-27CB-4E00-A5F0-62AE23D536EE} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {020874FC-11A2-4FC7-8929-527462F8819A} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {3411D565-223A-44B5-864C-E30F826001B4} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {ECA6E734-3908-45B4-9DFA-FDDA49AD620D} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0C041643-1217-466B-AF2E-1E44C7B117B1} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {6DB8DE55-5419-48EA-B4CD-2880E00409FB} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0A738527-821F-4089-B64E-3C0F4714DC78} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {EA9E6747-867B-4312-94B3-624EEB1C7A7A} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {EB889E78-AE59-4D41-AC29-8BC4D58BCE16} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0A021166-613C-430C-8460-50F1E0DF7AD8} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {1E3D564C-A79E-4E28-8E13-626EE7780831} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {973CE6DA-B55D-4E55-88D5-53BE69D44410} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {8845E6FF-94B2-4994-A8F4-DF30844A2168} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {99C8FB58-8718-4E76-AEFA-3C42F2F729B1} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {B729474D-0E96-4296-B317-450EE24F6B48} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {D466E363-F930-4D26-AE55-0256182961DD} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {25C5119A-AAFB-4C74-9E12-F747CA4D80E7} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0BC9E4F4-5C34-4B90-80AB-2933992D99A6} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {A5DD36AF-F0AD-4616-AB91-BC63E89B2744} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {B41AA17B-5129-41CC-8EA4-250B80BABF87} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0813853E-8C78-429A-B01A-3FB2EF1898F8} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {1B235247-6666-4B62-95A4-AC043626FDEA} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {5F6EF6F2-A742-445B-9418-682188F61130} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {C00722C2-E56B-424F-9216-FA6A91788986} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {90DD4D77-E3DC-456E-A27F-F13DA6194481} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {B69B7D59-6E7D-43FC-B83F-AA481B677B06} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {971198CC-ACB9-4718-9024-42A87E02E503} EndGlobalSection EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{BCAE2699-A994-48FE-B9B0-5580D267BD2E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bcl.AsyncInterfaces", "..\Microsoft.Bcl.AsyncInterfaces\ref\Microsoft.Bcl.AsyncInterfaces.csproj", "{47ACDB6F-34CB-478D-9E43-F3662EE5838D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bcl.AsyncInterfaces", "..\Microsoft.Bcl.AsyncInterfaces\src\Microsoft.Bcl.AsyncInterfaces.csproj", "{C24E4188-27CB-4E00-A5F0-62AE23D536EE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Abstractions", "..\Microsoft.Extensions.Configuration.Abstractions\ref\Microsoft.Extensions.Configuration.Abstractions.csproj", "{EDAC3418-1D4E-4216-9371-0A36EA1E13FE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Abstractions", "..\Microsoft.Extensions.Configuration.Abstractions\src\Microsoft.Extensions.Configuration.Abstractions.csproj", "{020874FC-11A2-4FC7-8929-527462F8819A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Binder", "..\Microsoft.Extensions.Configuration.Binder\ref\Microsoft.Extensions.Configuration.Binder.csproj", "{670AB88D-85C9-4674-A652-C27488ED73F9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Binder", "..\Microsoft.Extensions.Configuration.Binder\src\Microsoft.Extensions.Configuration.Binder.csproj", "{3411D565-223A-44B5-864C-E30F826001B4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.CommandLine", "..\Microsoft.Extensions.Configuration.CommandLine\ref\Microsoft.Extensions.Configuration.CommandLine.csproj", "{4AB3E652-6709-4011-AC2F-C379A0415BAC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.CommandLine", "..\Microsoft.Extensions.Configuration.CommandLine\src\Microsoft.Extensions.Configuration.CommandLine.csproj", "{ECA6E734-3908-45B4-9DFA-FDDA49AD620D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.EnvironmentVariables", "..\Microsoft.Extensions.Configuration.EnvironmentVariables\ref\Microsoft.Extensions.Configuration.EnvironmentVariables.csproj", "{3D657A5A-C7DF-4817-864F-944755DCE6DF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.EnvironmentVariables", "..\Microsoft.Extensions.Configuration.EnvironmentVariables\src\Microsoft.Extensions.Configuration.EnvironmentVariables.csproj", "{0C041643-1217-466B-AF2E-1E44C7B117B1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.FileExtensions", "..\Microsoft.Extensions.Configuration.FileExtensions\ref\Microsoft.Extensions.Configuration.FileExtensions.csproj", "{BD938E1D-6FC8-4D46-B103-B4D35761CEA2}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.FileExtensions", "..\Microsoft.Extensions.Configuration.FileExtensions\src\Microsoft.Extensions.Configuration.FileExtensions.csproj", "{6DB8DE55-5419-48EA-B4CD-2880E00409FB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Json", "..\Microsoft.Extensions.Configuration.Json\ref\Microsoft.Extensions.Configuration.Json.csproj", "{1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.Json", "..\Microsoft.Extensions.Configuration.Json\src\Microsoft.Extensions.Configuration.Json.csproj", "{0A738527-821F-4089-B64E-3C0F4714DC78}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.UserSecrets", "..\Microsoft.Extensions.Configuration.UserSecrets\ref\Microsoft.Extensions.Configuration.UserSecrets.csproj", "{37A36947-2652-4AFD-BCF8-AAFD4D4D2827}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration.UserSecrets", "..\Microsoft.Extensions.Configuration.UserSecrets\src\Microsoft.Extensions.Configuration.UserSecrets.csproj", "{EA9E6747-867B-4312-94B3-624EEB1C7A7A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration", "..\Microsoft.Extensions.Configuration\ref\Microsoft.Extensions.Configuration.csproj", "{13BC7AAA-7831-4500-9D28-A93FA4CA3C74}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Configuration", "..\Microsoft.Extensions.Configuration\src\Microsoft.Extensions.Configuration.csproj", "{EB889E78-AE59-4D41-AC29-8BC4D58BCE16}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection.Abstractions", "..\Microsoft.Extensions.DependencyInjection.Abstractions\ref\Microsoft.Extensions.DependencyInjection.Abstractions.csproj", "{135F551E-ACB8-4073-ABB5-A1FA558455DE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection.Abstractions", "..\Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj", "{0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection", "..\Microsoft.Extensions.DependencyInjection\ref\Microsoft.Extensions.DependencyInjection.csproj", "{5532E155-E423-4FFD-B009-80B4281D36BA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DependencyInjection", "..\Microsoft.Extensions.DependencyInjection\src\Microsoft.Extensions.DependencyInjection.csproj", "{6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Abstractions", "..\Microsoft.Extensions.FileProviders.Abstractions\ref\Microsoft.Extensions.FileProviders.Abstractions.csproj", "{24220AD7-03ED-427A-BFC8-114C475EAD0F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Abstractions", "..\Microsoft.Extensions.FileProviders.Abstractions\src\Microsoft.Extensions.FileProviders.Abstractions.csproj", "{0A021166-613C-430C-8460-50F1E0DF7AD8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Physical", "..\Microsoft.Extensions.FileProviders.Physical\ref\Microsoft.Extensions.FileProviders.Physical.csproj", "{376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileProviders.Physical", "..\Microsoft.Extensions.FileProviders.Physical\src\Microsoft.Extensions.FileProviders.Physical.csproj", "{1E3D564C-A79E-4E28-8E13-626EE7780831}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileSystemGlobbing", "..\Microsoft.Extensions.FileSystemGlobbing\ref\Microsoft.Extensions.FileSystemGlobbing.csproj", "{E4157F2E-F11D-48C6-A146-B4D12D9211F7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.FileSystemGlobbing", "..\Microsoft.Extensions.FileSystemGlobbing\src\Microsoft.Extensions.FileSystemGlobbing.csproj", "{9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Abstractions", "..\Microsoft.Extensions.Hosting.Abstractions\ref\Microsoft.Extensions.Hosting.Abstractions.csproj", "{2F25C0DB-E010-4802-8030-C88E2D09D3B0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Abstractions", "..\Microsoft.Extensions.Hosting.Abstractions\src\Microsoft.Extensions.Hosting.Abstractions.csproj", "{973CE6DA-B55D-4E55-88D5-53BE69D44410}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting", "ref\Microsoft.Extensions.Hosting.csproj", "{0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting", "src\Microsoft.Extensions.Hosting.csproj", "{F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Functional.Tests", "tests\FunctionalTests\Microsoft.Extensions.Hosting.Functional.Tests.csproj", "{2A882DCC-96C1-4EDF-A7F0-B526EC81533F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.TestApp", "tests\TestApp\Microsoft.Extensions.Hosting.TestApp.csproj", "{495208B7-31BB-4802-A769-CEE4917BDF75}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Unit.Tests", "tests\UnitTests\Microsoft.Extensions.Hosting.Unit.Tests.csproj", "{33C3D8F0-297F-4471-92B0-F4E8717F10E3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators.Roslyn3.11", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn3.11.csproj", "{1B235247-6666-4B62-95A4-AC043626FDEA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators.Roslyn4.0", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn4.0.csproj", "{5F6EF6F2-A742-445B-9418-682188F61130}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Abstractions", "..\Microsoft.Extensions.Logging.Abstractions\ref\Microsoft.Extensions.Logging.Abstractions.csproj", "{42E1BF94-6FE0-4017-9702-55913BD95EDE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Abstractions", "..\Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj", "{8845E6FF-94B2-4994-A8F4-DF30844A2168}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Configuration", "..\Microsoft.Extensions.Logging.Configuration\ref\Microsoft.Extensions.Logging.Configuration.csproj", "{15AD68F8-6C58-41A3-99B3-558C42A6E7A5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Configuration", "..\Microsoft.Extensions.Logging.Configuration\src\Microsoft.Extensions.Logging.Configuration.csproj", "{99C8FB58-8718-4E76-AEFA-3C42F2F729B1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Console", "..\Microsoft.Extensions.Logging.Console\ref\Microsoft.Extensions.Logging.Console.csproj", "{28C9D427-83BA-46A6-BEF5-6994A07F2258}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Console", "..\Microsoft.Extensions.Logging.Console\src\Microsoft.Extensions.Logging.Console.csproj", "{F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Debug", "..\Microsoft.Extensions.Logging.Debug\ref\Microsoft.Extensions.Logging.Debug.csproj", "{098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Debug", "..\Microsoft.Extensions.Logging.Debug\src\Microsoft.Extensions.Logging.Debug.csproj", "{B729474D-0E96-4296-B317-450EE24F6B48}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventLog", "..\Microsoft.Extensions.Logging.EventLog\ref\Microsoft.Extensions.Logging.EventLog.csproj", "{9ADBD2EE-D390-490C-BBEA-F844FE6F371E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventLog", "..\Microsoft.Extensions.Logging.EventLog\src\Microsoft.Extensions.Logging.EventLog.csproj", "{2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventSource", "..\Microsoft.Extensions.Logging.EventSource\ref\Microsoft.Extensions.Logging.EventSource.csproj", "{465AE1C4-84DD-4864-916A-74D89DC3BBBC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.EventSource", "..\Microsoft.Extensions.Logging.EventSource\src\Microsoft.Extensions.Logging.EventSource.csproj", "{D466E363-F930-4D26-AE55-0256182961DD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging", "..\Microsoft.Extensions.Logging\ref\Microsoft.Extensions.Logging.csproj", "{D69326FC-CD05-4690-91C0-1537A80ACBFF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging", "..\Microsoft.Extensions.Logging\src\Microsoft.Extensions.Logging.csproj", "{518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options.ConfigurationExtensions", "..\Microsoft.Extensions.Options.ConfigurationExtensions\ref\Microsoft.Extensions.Options.ConfigurationExtensions.csproj", "{014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options.ConfigurationExtensions", "..\Microsoft.Extensions.Options.ConfigurationExtensions\src\Microsoft.Extensions.Options.ConfigurationExtensions.csproj", "{0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options", "..\Microsoft.Extensions.Options\ref\Microsoft.Extensions.Options.csproj", "{DD121F9F-3548-4247-8E10-FB584FC0827C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Options", "..\Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj", "{25C5119A-AAFB-4C74-9E12-F747CA4D80E7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Primitives", "..\Microsoft.Extensions.Primitives\ref\Microsoft.Extensions.Primitives.csproj", "{45235656-E284-4682-BE70-9A284FD73243}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Primitives", "..\Microsoft.Extensions.Primitives\src\Microsoft.Extensions.Primitives.csproj", "{D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.DiagnosticSource", "..\System.Diagnostics.DiagnosticSource\ref\System.Diagnostics.DiagnosticSource.csproj", "{28726AEF-2732-4832-8930-074ACD9DC732}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.DiagnosticSource", "..\System.Diagnostics.DiagnosticSource\src\System.Diagnostics.DiagnosticSource.csproj", "{0BC9E4F4-5C34-4B90-80AB-2933992D99A6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.EventLog", "..\System.Diagnostics.EventLog\ref\System.Diagnostics.EventLog.csproj", "{34ECA788-A105-411B-AE8B-17B7CC1D703D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.EventLog.Messages", "..\System.Diagnostics.EventLog\src\Messages\System.Diagnostics.EventLog.Messages.csproj", "{A5DD36AF-F0AD-4616-AB91-BC63E89B2744}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.EventLog", "..\System.Diagnostics.EventLog\src\System.Diagnostics.EventLog.csproj", "{4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Drawing.Common", "..\System.Drawing.Common\ref\System.Drawing.Common.csproj", "{EB6CB1A4-1D66-49B8-9914-BA12B47C909F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{C00722C2-E56B-424F-9216-FA6A91788986}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{90DD4D77-E3DC-456E-A27F-F13DA6194481}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Permissions", "..\System.Security.Permissions\ref\System.Security.Permissions.csproj", "{FEC2349C-D18C-40B0-BA21-2111E383E972}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Encodings.Web", "..\System.Text.Encodings.Web\ref\System.Text.Encodings.Web.csproj", "{C595A27A-FA05-4BC8-9048-402338D7AF76}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Encodings.Web", "..\System.Text.Encodings.Web\src\System.Text.Encodings.Web.csproj", "{B41AA17B-5129-41CC-8EA4-250B80BABF87}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration.Roslyn3.11", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn3.11.csproj", "{0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration.Roslyn4.0", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn4.0.csproj", "{B69B7D59-6E7D-43FC-B83F-AA481B677B06}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json", "..\System.Text.Json\ref\System.Text.Json.csproj", "{1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json", "..\System.Text.Json\src\System.Text.Json.csproj", "{0813853E-8C78-429A-B01A-3FB2EF1898F8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Windows.Extensions", "..\System.Windows.Extensions\ref\System.Windows.Extensions.csproj", "{C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{E041754F-1A93-443A-9294-87DC1C30B471}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{59A29BF0-B76B-41F8-A733-E2A0847AB992}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{A9A8D649-4C09-4FD1-9837-EE7B9D902253}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Debug|Any CPU.Build.0 = Debug|Any CPU {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Release|Any CPU.ActiveCfg = Release|Any CPU {BCAE2699-A994-48FE-B9B0-5580D267BD2E}.Release|Any CPU.Build.0 = Release|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Debug|Any CPU.Build.0 = Debug|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Release|Any CPU.ActiveCfg = Release|Any CPU {47ACDB6F-34CB-478D-9E43-F3662EE5838D}.Release|Any CPU.Build.0 = Release|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Debug|Any CPU.Build.0 = Debug|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Release|Any CPU.ActiveCfg = Release|Any CPU {C24E4188-27CB-4E00-A5F0-62AE23D536EE}.Release|Any CPU.Build.0 = Release|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDAC3418-1D4E-4216-9371-0A36EA1E13FE}.Release|Any CPU.Build.0 = Release|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Debug|Any CPU.Build.0 = Debug|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Release|Any CPU.ActiveCfg = Release|Any CPU {020874FC-11A2-4FC7-8929-527462F8819A}.Release|Any CPU.Build.0 = Release|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {670AB88D-85C9-4674-A652-C27488ED73F9}.Release|Any CPU.Build.0 = Release|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Debug|Any CPU.Build.0 = Debug|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Release|Any CPU.ActiveCfg = Release|Any CPU {3411D565-223A-44B5-864C-E30F826001B4}.Release|Any CPU.Build.0 = Release|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Debug|Any CPU.Build.0 = Debug|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Release|Any CPU.ActiveCfg = Release|Any CPU {4AB3E652-6709-4011-AC2F-C379A0415BAC}.Release|Any CPU.Build.0 = Release|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Debug|Any CPU.Build.0 = Debug|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Release|Any CPU.ActiveCfg = Release|Any CPU {ECA6E734-3908-45B4-9DFA-FDDA49AD620D}.Release|Any CPU.Build.0 = Release|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Debug|Any CPU.Build.0 = Debug|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Release|Any CPU.ActiveCfg = Release|Any CPU {3D657A5A-C7DF-4817-864F-944755DCE6DF}.Release|Any CPU.Build.0 = Release|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {0C041643-1217-466B-AF2E-1E44C7B117B1}.Release|Any CPU.Build.0 = Release|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Debug|Any CPU.Build.0 = Debug|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Release|Any CPU.ActiveCfg = Release|Any CPU {BD938E1D-6FC8-4D46-B103-B4D35761CEA2}.Release|Any CPU.Build.0 = Release|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Debug|Any CPU.Build.0 = Debug|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Release|Any CPU.ActiveCfg = Release|Any CPU {6DB8DE55-5419-48EA-B4CD-2880E00409FB}.Release|Any CPU.Build.0 = Release|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Debug|Any CPU.Build.0 = Debug|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Release|Any CPU.ActiveCfg = Release|Any CPU {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC}.Release|Any CPU.Build.0 = Release|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A738527-821F-4089-B64E-3C0F4714DC78}.Release|Any CPU.Build.0 = Release|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Debug|Any CPU.Build.0 = Debug|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Release|Any CPU.ActiveCfg = Release|Any CPU {37A36947-2652-4AFD-BCF8-AAFD4D4D2827}.Release|Any CPU.Build.0 = Release|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Debug|Any CPU.Build.0 = Debug|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Release|Any CPU.ActiveCfg = Release|Any CPU {EA9E6747-867B-4312-94B3-624EEB1C7A7A}.Release|Any CPU.Build.0 = Release|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Debug|Any CPU.Build.0 = Debug|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Release|Any CPU.ActiveCfg = Release|Any CPU {13BC7AAA-7831-4500-9D28-A93FA4CA3C74}.Release|Any CPU.Build.0 = Release|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Debug|Any CPU.Build.0 = Debug|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Release|Any CPU.ActiveCfg = Release|Any CPU {EB889E78-AE59-4D41-AC29-8BC4D58BCE16}.Release|Any CPU.Build.0 = Release|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Debug|Any CPU.Build.0 = Debug|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Release|Any CPU.ActiveCfg = Release|Any CPU {135F551E-ACB8-4073-ABB5-A1FA558455DE}.Release|Any CPU.Build.0 = Release|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Debug|Any CPU.Build.0 = Debug|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Release|Any CPU.ActiveCfg = Release|Any CPU {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7}.Release|Any CPU.Build.0 = Release|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Debug|Any CPU.Build.0 = Debug|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Release|Any CPU.ActiveCfg = Release|Any CPU {5532E155-E423-4FFD-B009-80B4281D36BA}.Release|Any CPU.Build.0 = Release|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Debug|Any CPU.Build.0 = Debug|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Release|Any CPU.ActiveCfg = Release|Any CPU {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F}.Release|Any CPU.Build.0 = Release|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Debug|Any CPU.Build.0 = Debug|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Release|Any CPU.ActiveCfg = Release|Any CPU {24220AD7-03ED-427A-BFC8-114C475EAD0F}.Release|Any CPU.Build.0 = Release|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A021166-613C-430C-8460-50F1E0DF7AD8}.Release|Any CPU.Build.0 = Release|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Debug|Any CPU.Build.0 = Debug|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Release|Any CPU.ActiveCfg = Release|Any CPU {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F}.Release|Any CPU.Build.0 = Release|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Release|Any CPU.ActiveCfg = Release|Any CPU {1E3D564C-A79E-4E28-8E13-626EE7780831}.Release|Any CPU.Build.0 = Release|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Debug|Any CPU.Build.0 = Debug|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Release|Any CPU.ActiveCfg = Release|Any CPU {E4157F2E-F11D-48C6-A146-B4D12D9211F7}.Release|Any CPU.Build.0 = Release|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Debug|Any CPU.Build.0 = Debug|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Release|Any CPU.ActiveCfg = Release|Any CPU {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0}.Release|Any CPU.Build.0 = Release|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F25C0DB-E010-4802-8030-C88E2D09D3B0}.Release|Any CPU.Build.0 = Release|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Debug|Any CPU.Build.0 = Debug|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Release|Any CPU.ActiveCfg = Release|Any CPU {973CE6DA-B55D-4E55-88D5-53BE69D44410}.Release|Any CPU.Build.0 = Release|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Debug|Any CPU.Build.0 = Debug|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Release|Any CPU.ActiveCfg = Release|Any CPU {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84}.Release|Any CPU.Build.0 = Release|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D}.Release|Any CPU.Build.0 = Release|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A882DCC-96C1-4EDF-A7F0-B526EC81533F}.Release|Any CPU.Build.0 = Release|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Debug|Any CPU.Build.0 = Debug|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Release|Any CPU.ActiveCfg = Release|Any CPU {495208B7-31BB-4802-A769-CEE4917BDF75}.Release|Any CPU.Build.0 = Release|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Debug|Any CPU.Build.0 = Debug|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Release|Any CPU.ActiveCfg = Release|Any CPU {33C3D8F0-297F-4471-92B0-F4E8717F10E3}.Release|Any CPU.Build.0 = Release|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Debug|Any CPU.Build.0 = Debug|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Release|Any CPU.ActiveCfg = Release|Any CPU {1B235247-6666-4B62-95A4-AC043626FDEA}.Release|Any CPU.Build.0 = Release|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Debug|Any CPU.Build.0 = Debug|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Release|Any CPU.ActiveCfg = Release|Any CPU {5F6EF6F2-A742-445B-9418-682188F61130}.Release|Any CPU.Build.0 = Release|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Debug|Any CPU.Build.0 = Debug|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Release|Any CPU.ActiveCfg = Release|Any CPU {42E1BF94-6FE0-4017-9702-55913BD95EDE}.Release|Any CPU.Build.0 = Release|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Debug|Any CPU.Build.0 = Debug|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Release|Any CPU.ActiveCfg = Release|Any CPU {8845E6FF-94B2-4994-A8F4-DF30844A2168}.Release|Any CPU.Build.0 = Release|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Debug|Any CPU.Build.0 = Debug|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {15AD68F8-6C58-41A3-99B3-558C42A6E7A5}.Release|Any CPU.Build.0 = Release|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {99C8FB58-8718-4E76-AEFA-3C42F2F729B1}.Release|Any CPU.Build.0 = Release|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Debug|Any CPU.Build.0 = Debug|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Release|Any CPU.ActiveCfg = Release|Any CPU {28C9D427-83BA-46A6-BEF5-6994A07F2258}.Release|Any CPU.Build.0 = Release|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Debug|Any CPU.Build.0 = Debug|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Release|Any CPU.ActiveCfg = Release|Any CPU {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9}.Release|Any CPU.Build.0 = Release|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Debug|Any CPU.Build.0 = Debug|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Release|Any CPU.ActiveCfg = Release|Any CPU {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B}.Release|Any CPU.Build.0 = Release|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Debug|Any CPU.Build.0 = Debug|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Release|Any CPU.ActiveCfg = Release|Any CPU {B729474D-0E96-4296-B317-450EE24F6B48}.Release|Any CPU.Build.0 = Release|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Debug|Any CPU.Build.0 = Debug|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Release|Any CPU.ActiveCfg = Release|Any CPU {9ADBD2EE-D390-490C-BBEA-F844FE6F371E}.Release|Any CPU.Build.0 = Release|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Debug|Any CPU.Build.0 = Debug|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Release|Any CPU.ActiveCfg = Release|Any CPU {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295}.Release|Any CPU.Build.0 = Release|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Debug|Any CPU.Build.0 = Debug|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Release|Any CPU.ActiveCfg = Release|Any CPU {465AE1C4-84DD-4864-916A-74D89DC3BBBC}.Release|Any CPU.Build.0 = Release|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Debug|Any CPU.Build.0 = Debug|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {D466E363-F930-4D26-AE55-0256182961DD}.Release|Any CPU.Build.0 = Release|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Debug|Any CPU.Build.0 = Debug|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Release|Any CPU.ActiveCfg = Release|Any CPU {D69326FC-CD05-4690-91C0-1537A80ACBFF}.Release|Any CPU.Build.0 = Release|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Debug|Any CPU.Build.0 = Debug|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Release|Any CPU.ActiveCfg = Release|Any CPU {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19}.Release|Any CPU.Build.0 = Release|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Debug|Any CPU.Build.0 = Debug|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Release|Any CPU.ActiveCfg = Release|Any CPU {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E}.Release|Any CPU.Build.0 = Release|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Debug|Any CPU.Build.0 = Debug|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Release|Any CPU.ActiveCfg = Release|Any CPU {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1}.Release|Any CPU.Build.0 = Release|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Debug|Any CPU.Build.0 = Debug|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Release|Any CPU.ActiveCfg = Release|Any CPU {DD121F9F-3548-4247-8E10-FB584FC0827C}.Release|Any CPU.Build.0 = Release|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {25C5119A-AAFB-4C74-9E12-F747CA4D80E7}.Release|Any CPU.Build.0 = Release|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Debug|Any CPU.Build.0 = Debug|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Release|Any CPU.ActiveCfg = Release|Any CPU {45235656-E284-4682-BE70-9A284FD73243}.Release|Any CPU.Build.0 = Release|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Debug|Any CPU.Build.0 = Debug|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Release|Any CPU.ActiveCfg = Release|Any CPU {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A}.Release|Any CPU.Build.0 = Release|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Debug|Any CPU.Build.0 = Debug|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Release|Any CPU.ActiveCfg = Release|Any CPU {28726AEF-2732-4832-8930-074ACD9DC732}.Release|Any CPU.Build.0 = Release|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {0BC9E4F4-5C34-4B90-80AB-2933992D99A6}.Release|Any CPU.Build.0 = Release|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Debug|Any CPU.Build.0 = Debug|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Release|Any CPU.ActiveCfg = Release|Any CPU {34ECA788-A105-411B-AE8B-17B7CC1D703D}.Release|Any CPU.Build.0 = Release|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Debug|Any CPU.Build.0 = Debug|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Release|Any CPU.ActiveCfg = Release|Any CPU {A5DD36AF-F0AD-4616-AB91-BC63E89B2744}.Release|Any CPU.Build.0 = Release|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Debug|Any CPU.Build.0 = Debug|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Release|Any CPU.ActiveCfg = Release|Any CPU {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B}.Release|Any CPU.Build.0 = Release|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Debug|Any CPU.Build.0 = Debug|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Release|Any CPU.ActiveCfg = Release|Any CPU {EB6CB1A4-1D66-49B8-9914-BA12B47C909F}.Release|Any CPU.Build.0 = Release|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Debug|Any CPU.Build.0 = Debug|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Release|Any CPU.ActiveCfg = Release|Any CPU {C00722C2-E56B-424F-9216-FA6A91788986}.Release|Any CPU.Build.0 = Release|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Debug|Any CPU.Build.0 = Debug|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Release|Any CPU.ActiveCfg = Release|Any CPU {90DD4D77-E3DC-456E-A27F-F13DA6194481}.Release|Any CPU.Build.0 = Release|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Debug|Any CPU.Build.0 = Debug|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Release|Any CPU.ActiveCfg = Release|Any CPU {FEC2349C-D18C-40B0-BA21-2111E383E972}.Release|Any CPU.Build.0 = Release|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Debug|Any CPU.Build.0 = Debug|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Release|Any CPU.ActiveCfg = Release|Any CPU {C595A27A-FA05-4BC8-9048-402338D7AF76}.Release|Any CPU.Build.0 = Release|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Debug|Any CPU.Build.0 = Debug|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Release|Any CPU.ActiveCfg = Release|Any CPU {B41AA17B-5129-41CC-8EA4-250B80BABF87}.Release|Any CPU.Build.0 = Release|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5}.Release|Any CPU.Build.0 = Release|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Debug|Any CPU.Build.0 = Debug|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Release|Any CPU.ActiveCfg = Release|Any CPU {B69B7D59-6E7D-43FC-B83F-AA481B677B06}.Release|Any CPU.Build.0 = Release|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Release|Any CPU.ActiveCfg = Release|Any CPU {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952}.Release|Any CPU.Build.0 = Release|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Debug|Any CPU.Build.0 = Debug|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Release|Any CPU.ActiveCfg = Release|Any CPU {0813853E-8C78-429A-B01A-3FB2EF1898F8}.Release|Any CPU.Build.0 = Release|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Debug|Any CPU.Build.0 = Debug|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Release|Any CPU.ActiveCfg = Release|Any CPU {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {BCAE2699-A994-48FE-B9B0-5580D267BD2E} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {2A882DCC-96C1-4EDF-A7F0-B526EC81533F} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {495208B7-31BB-4802-A769-CEE4917BDF75} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {33C3D8F0-297F-4471-92B0-F4E8717F10E3} = {06E9ED4F-D3CF-4216-A8C7-E8A0AB16E33D} {47ACDB6F-34CB-478D-9E43-F3662EE5838D} = {E041754F-1A93-443A-9294-87DC1C30B471} {EDAC3418-1D4E-4216-9371-0A36EA1E13FE} = {E041754F-1A93-443A-9294-87DC1C30B471} {670AB88D-85C9-4674-A652-C27488ED73F9} = {E041754F-1A93-443A-9294-87DC1C30B471} {4AB3E652-6709-4011-AC2F-C379A0415BAC} = {E041754F-1A93-443A-9294-87DC1C30B471} {3D657A5A-C7DF-4817-864F-944755DCE6DF} = {E041754F-1A93-443A-9294-87DC1C30B471} {BD938E1D-6FC8-4D46-B103-B4D35761CEA2} = {E041754F-1A93-443A-9294-87DC1C30B471} {1C07ECD0-F69E-4E35-9C68-E4063B5D97EC} = {E041754F-1A93-443A-9294-87DC1C30B471} {37A36947-2652-4AFD-BCF8-AAFD4D4D2827} = {E041754F-1A93-443A-9294-87DC1C30B471} {13BC7AAA-7831-4500-9D28-A93FA4CA3C74} = {E041754F-1A93-443A-9294-87DC1C30B471} {135F551E-ACB8-4073-ABB5-A1FA558455DE} = {E041754F-1A93-443A-9294-87DC1C30B471} {5532E155-E423-4FFD-B009-80B4281D36BA} = {E041754F-1A93-443A-9294-87DC1C30B471} {24220AD7-03ED-427A-BFC8-114C475EAD0F} = {E041754F-1A93-443A-9294-87DC1C30B471} {376BB9D1-6C3E-4BB1-B13A-F0750D2BE01F} = {E041754F-1A93-443A-9294-87DC1C30B471} {E4157F2E-F11D-48C6-A146-B4D12D9211F7} = {E041754F-1A93-443A-9294-87DC1C30B471} {2F25C0DB-E010-4802-8030-C88E2D09D3B0} = {E041754F-1A93-443A-9294-87DC1C30B471} {0D7771CB-B3D1-4FF4-A523-40BFD3B12A84} = {E041754F-1A93-443A-9294-87DC1C30B471} {42E1BF94-6FE0-4017-9702-55913BD95EDE} = {E041754F-1A93-443A-9294-87DC1C30B471} {15AD68F8-6C58-41A3-99B3-558C42A6E7A5} = {E041754F-1A93-443A-9294-87DC1C30B471} {28C9D427-83BA-46A6-BEF5-6994A07F2258} = {E041754F-1A93-443A-9294-87DC1C30B471} {098CEEE6-91D3-4A7C-A5D5-6BB329BB2B7B} = {E041754F-1A93-443A-9294-87DC1C30B471} {9ADBD2EE-D390-490C-BBEA-F844FE6F371E} = {E041754F-1A93-443A-9294-87DC1C30B471} {465AE1C4-84DD-4864-916A-74D89DC3BBBC} = {E041754F-1A93-443A-9294-87DC1C30B471} {D69326FC-CD05-4690-91C0-1537A80ACBFF} = {E041754F-1A93-443A-9294-87DC1C30B471} {014EE6B4-BE08-4E50-9EBD-0D7A0CB7A76E} = {E041754F-1A93-443A-9294-87DC1C30B471} {DD121F9F-3548-4247-8E10-FB584FC0827C} = {E041754F-1A93-443A-9294-87DC1C30B471} {45235656-E284-4682-BE70-9A284FD73243} = {E041754F-1A93-443A-9294-87DC1C30B471} {28726AEF-2732-4832-8930-074ACD9DC732} = {E041754F-1A93-443A-9294-87DC1C30B471} {34ECA788-A105-411B-AE8B-17B7CC1D703D} = {E041754F-1A93-443A-9294-87DC1C30B471} {EB6CB1A4-1D66-49B8-9914-BA12B47C909F} = {E041754F-1A93-443A-9294-87DC1C30B471} {FEC2349C-D18C-40B0-BA21-2111E383E972} = {E041754F-1A93-443A-9294-87DC1C30B471} {C595A27A-FA05-4BC8-9048-402338D7AF76} = {E041754F-1A93-443A-9294-87DC1C30B471} {1E3D79D4-51D6-46C6-BF0F-DF51A47C5952} = {E041754F-1A93-443A-9294-87DC1C30B471} {C827FFA2-1AE3-47A7-9CF2-F3F56B2D8519} = {E041754F-1A93-443A-9294-87DC1C30B471} {C24E4188-27CB-4E00-A5F0-62AE23D536EE} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {020874FC-11A2-4FC7-8929-527462F8819A} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {3411D565-223A-44B5-864C-E30F826001B4} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {ECA6E734-3908-45B4-9DFA-FDDA49AD620D} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0C041643-1217-466B-AF2E-1E44C7B117B1} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {6DB8DE55-5419-48EA-B4CD-2880E00409FB} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0A738527-821F-4089-B64E-3C0F4714DC78} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {EA9E6747-867B-4312-94B3-624EEB1C7A7A} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {EB889E78-AE59-4D41-AC29-8BC4D58BCE16} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0EEA7382-25A8-4FB0-AE9A-4ECDF2FF6FB7} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {6C6DDBF6-AAF3-4A2A-8CB1-C7A630B7C49F} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0A021166-613C-430C-8460-50F1E0DF7AD8} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {1E3D564C-A79E-4E28-8E13-626EE7780831} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {9C06E60B-2D45-4284-B7C8-7AE6D8194CE0} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {973CE6DA-B55D-4E55-88D5-53BE69D44410} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {F5CF1FC4-8F56-49BD-BFC2-5AD42AE6302D} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {8845E6FF-94B2-4994-A8F4-DF30844A2168} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {99C8FB58-8718-4E76-AEFA-3C42F2F729B1} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {F3230087-28E2-4ADF-A7D1-D48C5D9CFFE9} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {B729474D-0E96-4296-B317-450EE24F6B48} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {2D4DBF5A-3BF4-4846-89F2-6FCDB80BF295} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {D466E363-F930-4D26-AE55-0256182961DD} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {518D4AE0-FBFF-493A-A2DF-8ACBA842AE19} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0AEAD15B-CD38-4462-A36C-655ED8D0CBD1} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {25C5119A-AAFB-4C74-9E12-F747CA4D80E7} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {D975AE29-0CA2-43FC-90A0-B266DF7D4C2A} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0BC9E4F4-5C34-4B90-80AB-2933992D99A6} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {A5DD36AF-F0AD-4616-AB91-BC63E89B2744} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {4ED9C0A9-C1EF-47ED-99F8-74B7411C971B} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {B41AA17B-5129-41CC-8EA4-250B80BABF87} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {0813853E-8C78-429A-B01A-3FB2EF1898F8} = {59A29BF0-B76B-41F8-A733-E2A0847AB992} {1B235247-6666-4B62-95A4-AC043626FDEA} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {5F6EF6F2-A742-445B-9418-682188F61130} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {C00722C2-E56B-424F-9216-FA6A91788986} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {90DD4D77-E3DC-456E-A27F-F13DA6194481} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {0A495D7B-44DE-4E59-8497-6CBF7C55CFA5} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} {B69B7D59-6E7D-43FC-B83F-AA481B677B06} = {A9A8D649-4C09-4FD1-9837-EE7B9D902253} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {971198CC-ACB9-4718-9024-42A87E02E503} EndGlobalSection EndGlobal
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/Xor.Int16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 XorInt16() { var test = new SimpleBinaryOpTest__XorInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__XorInt16 testClass) { var result = Sse2.Xor(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__XorInt16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__XorInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__XorInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Xor( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Xor( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pClsVar1)), Sse2.LoadVector128((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__XorInt16(); var result = Sse2.Xor(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__XorInt16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(&test._fld1)), Sse2.LoadVector128((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] ^ right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] ^ right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 XorInt16() { var test = new SimpleBinaryOpTest__XorInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__XorInt16 testClass) { var result = Sse2.Xor(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__XorInt16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__XorInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__XorInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Xor( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Xor( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pClsVar1)), Sse2.LoadVector128((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__XorInt16(); var result = Sse2.Xor(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__XorInt16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(&test._fld1)), Sse2.LoadVector128((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] ^ right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] ^ right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/SIMD/VectorMax_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="VectorMax.cs" /> <Compile Include="VectorUtil.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="VectorMax.cs" /> <Compile Include="VectorUtil.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/RssFeeds/cloud_path.xml
<!-- Description: cloud must include path attribute Expect: ValidCloud{element:cloud,attr:path} --> <rss version="2.0"> <channel> <title>Invalid cloud</title> <link>http://contoso.com/rss/2.0/</link> <description>foo</description> <cloud domain="contoso.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/> </channel> </rss>
<!-- Description: cloud must include path attribute Expect: ValidCloud{element:cloud,attr:path} --> <rss version="2.0"> <channel> <title>Invalid cloud</title> <link>http://contoso.com/rss/2.0/</link> <description>foo</description> <cloud domain="contoso.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/> </channel> </rss>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/add_ovf_u2.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .class public add_ovf_u2 { .method public static int32 u2(int32,int32,int32) { .locals (class [mscorlib]System.OverflowException, int32) .maxstack 2 try_start: ldarg 0 ldarg 1 add conv.ovf.u2 ldarg 2 ceq stloc.1 leave.s try_end try_end: ldloc.1 brfalse FAIL ldc.i4 0x11111111 br END aHandler: isinst [mscorlib]System.OverflowException stloc 0 leave HEnd HEnd: ldloc 0 brfalse FAIL ldc.i4 0xEEEEEEEE br END FAIL: ldc.i4 0x00000000 END: ret .try try_start to try_end catch [mscorlib]System.OverflowException handler aHandler to HEnd } .method public void add_ovf_u2() { .maxstack 0 ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 5 ldc.i4 0x00000000 ldc.i4 0x00000000 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00000001 ldc.i4 0x00000001 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x0000FFFE ldc.i4 0x0000FFFE call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x0000FFFF ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00005555 ldc.i4 0x00005555 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x0000AAAA ldc.i4 0x0000AAAA call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000000 ldc.i4 0x00000001 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000001 ldc.i4 0x00000002 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x0000FFFE ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00005555 ldc.i4 0x00005556 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x0000AAAA ldc.i4 0x0000AAAB call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x00000000 ldc.i4 0x0000FFFE call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x00000001 ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x00005555 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x0000AAAA ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x00000000 ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x00000001 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x00005555 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x0000AAAA ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x00000000 ldc.i4 0x00005555 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x00000001 ldc.i4 0x00005556 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x00005555 ldc.i4 0x0000AAAA call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x0000AAAA ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x00000000 ldc.i4 0x0000AAAA call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x00000001 ldc.i4 0x0000AAAB call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x00005555 ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x0000AAAA ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL PASS: ldc.i4 100 br END FAIL: ldc.i4 0x00000000 END: ret } } .assembly add_ovf_u2{}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .class public add_ovf_u2 { .method public static int32 u2(int32,int32,int32) { .locals (class [mscorlib]System.OverflowException, int32) .maxstack 2 try_start: ldarg 0 ldarg 1 add conv.ovf.u2 ldarg 2 ceq stloc.1 leave.s try_end try_end: ldloc.1 brfalse FAIL ldc.i4 0x11111111 br END aHandler: isinst [mscorlib]System.OverflowException stloc 0 leave HEnd HEnd: ldloc 0 brfalse FAIL ldc.i4 0xEEEEEEEE br END FAIL: ldc.i4 0x00000000 END: ret .try try_start to try_end catch [mscorlib]System.OverflowException handler aHandler to HEnd } .method public void add_ovf_u2() { .maxstack 0 ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 5 ldc.i4 0x00000000 ldc.i4 0x00000000 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00000001 ldc.i4 0x00000001 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x0000FFFE ldc.i4 0x0000FFFE call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x0000FFFF ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00005555 ldc.i4 0x00005555 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x0000AAAA ldc.i4 0x0000AAAA call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000000 ldc.i4 0x00000001 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000001 ldc.i4 0x00000002 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x0000FFFE ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00005555 ldc.i4 0x00005556 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x0000AAAA ldc.i4 0x0000AAAB call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x00000000 ldc.i4 0x0000FFFE call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x00000001 ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x00005555 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFE ldc.i4 0x0000AAAA ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x00000000 ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x00000001 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x00005555 ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000FFFF ldc.i4 0x0000AAAA ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x00000000 ldc.i4 0x00005555 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x00000001 ldc.i4 0x00005556 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x00005555 ldc.i4 0x0000AAAA call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00005555 ldc.i4 0x0000AAAA ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x00000000 ldc.i4 0x0000AAAA call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x00000001 ldc.i4 0x0000AAAB call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x0000FFFE ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x0000FFFF ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x00005555 ldc.i4 0x0000FFFF call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x0000AAAA ldc.i4 0x0000AAAA ldc.i4 0x00000000 call int32 add_ovf_u2::u2(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL PASS: ldc.i4 100 br END FAIL: ldc.i4 0x00000000 END: ret } } .assembly add_ovf_u2{}
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b32551/b32551b.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="b32551b.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="b32551b.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/coreclr/tools/Common/Compiler/VectorFieldLayoutAlgorithm.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler { /// <summary> /// Represents an algorithm that computes field layout for intrinsic vector types (Vector64/Vector128/Vector256). /// </summary> public class VectorFieldLayoutAlgorithm : FieldLayoutAlgorithm { private readonly FieldLayoutAlgorithm _fallbackAlgorithm; private readonly bool _vectorAbiIsStable; public VectorFieldLayoutAlgorithm(FieldLayoutAlgorithm fallbackAlgorithm, bool vectorAbiIsStable = true) { _vectorAbiIsStable = vectorAbiIsStable; _fallbackAlgorithm = fallbackAlgorithm; } public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType defType, InstanceLayoutKind layoutKind) { Debug.Assert(IsVectorType(defType)); LayoutInt alignment; string name = defType.Name; if (name == "Vector64`1") { alignment = new LayoutInt(8); } else if (name == "Vector128`1") { if (defType.Context.Target.Architecture == TargetArchitecture.ARM) { // The Procedure Call Standard for ARM defaults to 8-byte alignment for __m128 alignment = new LayoutInt(8); } else { alignment = new LayoutInt(16); } } else { Debug.Assert(name == "Vector256`1"); if (defType.Context.Target.Architecture == TargetArchitecture.ARM) { // No such type exists for the Procedure Call Standard for ARM. We will default // to the same alignment as __m128, which is supported by the ABI. alignment = new LayoutInt(8); } else if (defType.Context.Target.Architecture == TargetArchitecture.ARM64) { // The Procedure Call Standard for ARM 64-bit (with SVE support) defaults to // 16-byte alignment for __m256. alignment = new LayoutInt(16); } else { alignment = new LayoutInt(32); } } ComputedInstanceFieldLayout layoutFromMetadata = _fallbackAlgorithm.ComputeInstanceLayout(defType, layoutKind); return new ComputedInstanceFieldLayout { ByteCountUnaligned = layoutFromMetadata.ByteCountUnaligned, ByteCountAlignment = layoutFromMetadata.ByteCountAlignment, FieldAlignment = alignment, FieldSize = layoutFromMetadata.FieldSize, Offsets = layoutFromMetadata.Offsets, LayoutAbiStable = _vectorAbiIsStable }; } public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defType, StaticLayoutKind layoutKind) { return _fallbackAlgorithm.ComputeStaticFieldLayout(defType, layoutKind); } public override bool ComputeContainsGCPointers(DefType type) { Debug.Assert(!_fallbackAlgorithm.ComputeContainsGCPointers(type)); return false; } public override bool ComputeIsUnsafeValueType(DefType type) { Debug.Assert(!_fallbackAlgorithm.ComputeIsUnsafeValueType(type)); return false; } public override ValueTypeShapeCharacteristics ComputeValueTypeShapeCharacteristics(DefType type) { if (type.Context.Target.Architecture == TargetArchitecture.ARM64 && type.Instantiation[0].IsPrimitiveNumeric) { return type.InstanceFieldSize.AsInt switch { 8 => ValueTypeShapeCharacteristics.Vector64Aggregate, 16 => ValueTypeShapeCharacteristics.Vector128Aggregate, _ => ValueTypeShapeCharacteristics.None }; } return ValueTypeShapeCharacteristics.None; } public static bool IsVectorType(DefType type) { return type.IsIntrinsic && type.Namespace == "System.Runtime.Intrinsics" && (type.Name == "Vector64`1" || type.Name == "Vector128`1" || type.Name == "Vector256`1"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler { /// <summary> /// Represents an algorithm that computes field layout for intrinsic vector types (Vector64/Vector128/Vector256). /// </summary> public class VectorFieldLayoutAlgorithm : FieldLayoutAlgorithm { private readonly FieldLayoutAlgorithm _fallbackAlgorithm; private readonly bool _vectorAbiIsStable; public VectorFieldLayoutAlgorithm(FieldLayoutAlgorithm fallbackAlgorithm, bool vectorAbiIsStable = true) { _vectorAbiIsStable = vectorAbiIsStable; _fallbackAlgorithm = fallbackAlgorithm; } public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType defType, InstanceLayoutKind layoutKind) { Debug.Assert(IsVectorType(defType)); LayoutInt alignment; string name = defType.Name; if (name == "Vector64`1") { alignment = new LayoutInt(8); } else if (name == "Vector128`1") { if (defType.Context.Target.Architecture == TargetArchitecture.ARM) { // The Procedure Call Standard for ARM defaults to 8-byte alignment for __m128 alignment = new LayoutInt(8); } else { alignment = new LayoutInt(16); } } else { Debug.Assert(name == "Vector256`1"); if (defType.Context.Target.Architecture == TargetArchitecture.ARM) { // No such type exists for the Procedure Call Standard for ARM. We will default // to the same alignment as __m128, which is supported by the ABI. alignment = new LayoutInt(8); } else if (defType.Context.Target.Architecture == TargetArchitecture.ARM64) { // The Procedure Call Standard for ARM 64-bit (with SVE support) defaults to // 16-byte alignment for __m256. alignment = new LayoutInt(16); } else { alignment = new LayoutInt(32); } } ComputedInstanceFieldLayout layoutFromMetadata = _fallbackAlgorithm.ComputeInstanceLayout(defType, layoutKind); return new ComputedInstanceFieldLayout { ByteCountUnaligned = layoutFromMetadata.ByteCountUnaligned, ByteCountAlignment = layoutFromMetadata.ByteCountAlignment, FieldAlignment = alignment, FieldSize = layoutFromMetadata.FieldSize, Offsets = layoutFromMetadata.Offsets, LayoutAbiStable = _vectorAbiIsStable }; } public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defType, StaticLayoutKind layoutKind) { return _fallbackAlgorithm.ComputeStaticFieldLayout(defType, layoutKind); } public override bool ComputeContainsGCPointers(DefType type) { Debug.Assert(!_fallbackAlgorithm.ComputeContainsGCPointers(type)); return false; } public override bool ComputeIsUnsafeValueType(DefType type) { Debug.Assert(!_fallbackAlgorithm.ComputeIsUnsafeValueType(type)); return false; } public override ValueTypeShapeCharacteristics ComputeValueTypeShapeCharacteristics(DefType type) { if (type.Context.Target.Architecture == TargetArchitecture.ARM64 && type.Instantiation[0].IsPrimitiveNumeric) { return type.InstanceFieldSize.AsInt switch { 8 => ValueTypeShapeCharacteristics.Vector64Aggregate, 16 => ValueTypeShapeCharacteristics.Vector128Aggregate, _ => ValueTypeShapeCharacteristics.None }; } return ValueTypeShapeCharacteristics.None; } public static bool IsVectorType(DefType type) { return type.IsIntrinsic && type.Namespace == "System.Runtime.Intrinsics" && (type.Name == "Vector64`1" || type.Name == "Vector128`1" || type.Name == "Vector256`1"); } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/coreclr/nativeaot/nativeaot.sln
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30421.15 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "System.Private.CoreLib\src\System.Private.CoreLib.csproj", "{E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.DisabledReflection", "System.Private.DisabledReflection\src\System.Private.DisabledReflection.csproj", "{ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Interop", "System.Private.Interop\src\System.Private.Interop.csproj", "{BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Reflection.Core", "System.Private.Reflection.Core\src\System.Private.Reflection.Core.csproj", "{6147AF1A-5054-492A-9309-FA868A184414}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Reflection.Execution", "System.Private.Reflection.Execution\src\System.Private.Reflection.Execution.csproj", "{7498DD7C-76C1-4912-AF72-DA84E05B568F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Reflection.Metadata", "System.Private.Reflection.Metadata\src\System.Private.Reflection.Metadata.csproj", "{C0245BD9-6AE2-47A5-BC41-DB6F777423AF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.StackTraceMetadata", "System.Private.StackTraceMetadata\src\System.Private.StackTraceMetadata.csproj", "{33CAE331-16EE-443C-A0CC-4337B94A02AD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.TypeLoader", "System.Private.TypeLoader\src\System.Private.TypeLoader.csproj", "{3E43ACA2-073E-4A66-BA9C-417C5F83D430}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test.CoreLib", "Test.CoreLib\src\Test.CoreLib.csproj", "{C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "System.Private.CoreLib.Shared", "..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.shproj", "{977524B8-92D8-4DFC-91E4-11A0582B81BF}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{977524b8-92d8-4dfc-91e4-11a0582b81bf}*SharedItemsImports = 13 ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{e4bc768b-f97d-4a8f-9391-b65df3eb47c6}*SharedItemsImports = 5 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Checked|arm = Checked|arm Checked|arm64 = Checked|arm64 Checked|x64 = Checked|x64 Checked|x86 = Checked|x86 Debug|arm = Debug|arm Debug|arm64 = Debug|arm64 Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|arm = Release|arm Release|arm64 = Release|arm64 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm.ActiveCfg = Checked|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm.Build.0 = Checked|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm64.ActiveCfg = Checked|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm64.Build.0 = Checked|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x64.ActiveCfg = Checked|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x64.Build.0 = Checked|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x86.ActiveCfg = Checked|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x86.Build.0 = Checked|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm.ActiveCfg = Debug|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm.Build.0 = Debug|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm64.ActiveCfg = Debug|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm64.Build.0 = Debug|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x64.ActiveCfg = Debug|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x64.Build.0 = Debug|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x86.ActiveCfg = Debug|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x86.Build.0 = Debug|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm.ActiveCfg = Release|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm.Build.0 = Release|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm64.ActiveCfg = Release|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm64.Build.0 = Release|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x64.ActiveCfg = Release|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x64.Build.0 = Release|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x86.ActiveCfg = Release|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x86.Build.0 = Release|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm.ActiveCfg = Checked|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm.Build.0 = Checked|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm64.ActiveCfg = Checked|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm64.Build.0 = Checked|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x64.ActiveCfg = Checked|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x64.Build.0 = Checked|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x86.ActiveCfg = Checked|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x86.Build.0 = Checked|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm.ActiveCfg = Debug|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm.Build.0 = Debug|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm64.ActiveCfg = Debug|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm64.Build.0 = Debug|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x64.ActiveCfg = Debug|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x64.Build.0 = Debug|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x86.ActiveCfg = Debug|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x86.Build.0 = Debug|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm.ActiveCfg = Release|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm.Build.0 = Release|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm64.ActiveCfg = Release|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm64.Build.0 = Release|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x64.ActiveCfg = Release|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x64.Build.0 = Release|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x86.ActiveCfg = Release|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x86.Build.0 = Release|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm.ActiveCfg = Checked|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm.Build.0 = Checked|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm64.ActiveCfg = Checked|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm64.Build.0 = Checked|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x64.ActiveCfg = Checked|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x64.Build.0 = Checked|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x86.ActiveCfg = Checked|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x86.Build.0 = Checked|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm.ActiveCfg = Debug|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm.Build.0 = Debug|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm64.ActiveCfg = Debug|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm64.Build.0 = Debug|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x64.ActiveCfg = Debug|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x64.Build.0 = Debug|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x86.ActiveCfg = Debug|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x86.Build.0 = Debug|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm.ActiveCfg = Release|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm.Build.0 = Release|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm64.ActiveCfg = Release|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm64.Build.0 = Release|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x64.ActiveCfg = Release|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x64.Build.0 = Release|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x86.ActiveCfg = Release|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x86.Build.0 = Release|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm.ActiveCfg = Checked|arm {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm.Build.0 = Checked|arm {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm64.ActiveCfg = Checked|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm64.Build.0 = Checked|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x64.ActiveCfg = Checked|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x64.Build.0 = Checked|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x86.ActiveCfg = Checked|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x86.Build.0 = Checked|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm.ActiveCfg = Debug|arm {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm.Build.0 = Debug|arm {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm64.ActiveCfg = Debug|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm64.Build.0 = Debug|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x64.ActiveCfg = Debug|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x64.Build.0 = Debug|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x86.ActiveCfg = Debug|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x86.Build.0 = Debug|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm.ActiveCfg = Release|arm {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm.Build.0 = Release|arm {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm64.ActiveCfg = Release|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm64.Build.0 = Release|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x64.ActiveCfg = Release|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x64.Build.0 = Release|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x86.ActiveCfg = Release|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x86.Build.0 = Release|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm.ActiveCfg = Checked|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm.Build.0 = Checked|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm64.ActiveCfg = Checked|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm64.Build.0 = Checked|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x64.ActiveCfg = Checked|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x64.Build.0 = Checked|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x86.ActiveCfg = Checked|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x86.Build.0 = Checked|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm.ActiveCfg = Debug|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm.Build.0 = Debug|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm64.ActiveCfg = Debug|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm64.Build.0 = Debug|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x64.ActiveCfg = Debug|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x64.Build.0 = Debug|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x86.ActiveCfg = Debug|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x86.Build.0 = Debug|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm.ActiveCfg = Release|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm.Build.0 = Release|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm64.ActiveCfg = Release|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm64.Build.0 = Release|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x64.ActiveCfg = Release|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x64.Build.0 = Release|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x86.ActiveCfg = Release|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x86.Build.0 = Release|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm.ActiveCfg = Checked|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm.Build.0 = Checked|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm64.ActiveCfg = Checked|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm64.Build.0 = Checked|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x64.ActiveCfg = Checked|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x64.Build.0 = Checked|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x86.ActiveCfg = Checked|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x86.Build.0 = Checked|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm.ActiveCfg = Debug|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm.Build.0 = Debug|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm64.ActiveCfg = Debug|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm64.Build.0 = Debug|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x64.ActiveCfg = Debug|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x64.Build.0 = Debug|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x86.ActiveCfg = Debug|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x86.Build.0 = Debug|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm.ActiveCfg = Release|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm.Build.0 = Release|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm64.ActiveCfg = Release|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm64.Build.0 = Release|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x64.ActiveCfg = Release|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x64.Build.0 = Release|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x86.ActiveCfg = Release|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x86.Build.0 = Release|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm.ActiveCfg = Checked|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm.Build.0 = Checked|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm64.ActiveCfg = Checked|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm64.Build.0 = Checked|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x64.ActiveCfg = Checked|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x64.Build.0 = Checked|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x86.ActiveCfg = Checked|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x86.Build.0 = Checked|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm.ActiveCfg = Debug|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm.Build.0 = Debug|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm64.ActiveCfg = Debug|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm64.Build.0 = Debug|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x64.ActiveCfg = Debug|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x64.Build.0 = Debug|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x86.ActiveCfg = Debug|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x86.Build.0 = Debug|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm.ActiveCfg = Release|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm.Build.0 = Release|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm64.ActiveCfg = Release|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm64.Build.0 = Release|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x64.ActiveCfg = Release|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x64.Build.0 = Release|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x86.ActiveCfg = Release|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x86.Build.0 = Release|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm.ActiveCfg = Checked|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm.Build.0 = Checked|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm64.ActiveCfg = Checked|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm64.Build.0 = Checked|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x64.ActiveCfg = Checked|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x64.Build.0 = Checked|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x86.ActiveCfg = Checked|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x86.Build.0 = Checked|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm.ActiveCfg = Debug|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm.Build.0 = Debug|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm64.ActiveCfg = Debug|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm64.Build.0 = Debug|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x64.ActiveCfg = Debug|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x64.Build.0 = Debug|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x86.ActiveCfg = Debug|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x86.Build.0 = Debug|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm.ActiveCfg = Release|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm.Build.0 = Release|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm64.ActiveCfg = Release|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm64.Build.0 = Release|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x64.ActiveCfg = Release|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x64.Build.0 = Release|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x86.ActiveCfg = Release|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x86.Build.0 = Release|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm.ActiveCfg = Checked|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm.Build.0 = Checked|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm64.ActiveCfg = Checked|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm64.Build.0 = Checked|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x64.ActiveCfg = Checked|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x64.Build.0 = Checked|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x86.ActiveCfg = Checked|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x86.Build.0 = Checked|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm.ActiveCfg = Debug|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm.Build.0 = Debug|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm64.ActiveCfg = Debug|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm64.Build.0 = Debug|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x64.ActiveCfg = Debug|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x64.Build.0 = Debug|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x86.ActiveCfg = Debug|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x86.Build.0 = Debug|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm.ActiveCfg = Release|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm.Build.0 = Release|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm64.ActiveCfg = Release|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm64.Build.0 = Release|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x64.ActiveCfg = Release|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x64.Build.0 = Release|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x86.ActiveCfg = Release|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {81B16D59-928B-49C1-839D-10E4747B0DC0} EndGlobalSection EndGlobal
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30421.15 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "System.Private.CoreLib\src\System.Private.CoreLib.csproj", "{E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.DisabledReflection", "System.Private.DisabledReflection\src\System.Private.DisabledReflection.csproj", "{ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Interop", "System.Private.Interop\src\System.Private.Interop.csproj", "{BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Reflection.Core", "System.Private.Reflection.Core\src\System.Private.Reflection.Core.csproj", "{6147AF1A-5054-492A-9309-FA868A184414}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Reflection.Execution", "System.Private.Reflection.Execution\src\System.Private.Reflection.Execution.csproj", "{7498DD7C-76C1-4912-AF72-DA84E05B568F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.Reflection.Metadata", "System.Private.Reflection.Metadata\src\System.Private.Reflection.Metadata.csproj", "{C0245BD9-6AE2-47A5-BC41-DB6F777423AF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.StackTraceMetadata", "System.Private.StackTraceMetadata\src\System.Private.StackTraceMetadata.csproj", "{33CAE331-16EE-443C-A0CC-4337B94A02AD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.TypeLoader", "System.Private.TypeLoader\src\System.Private.TypeLoader.csproj", "{3E43ACA2-073E-4A66-BA9C-417C5F83D430}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test.CoreLib", "Test.CoreLib\src\Test.CoreLib.csproj", "{C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}" EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "System.Private.CoreLib.Shared", "..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.shproj", "{977524B8-92D8-4DFC-91E4-11A0582B81BF}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{977524b8-92d8-4dfc-91e4-11a0582b81bf}*SharedItemsImports = 13 ..\..\libraries\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{e4bc768b-f97d-4a8f-9391-b65df3eb47c6}*SharedItemsImports = 5 EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Checked|arm = Checked|arm Checked|arm64 = Checked|arm64 Checked|x64 = Checked|x64 Checked|x86 = Checked|x86 Debug|arm = Debug|arm Debug|arm64 = Debug|arm64 Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|arm = Release|arm Release|arm64 = Release|arm64 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm.ActiveCfg = Checked|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm.Build.0 = Checked|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm64.ActiveCfg = Checked|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|arm64.Build.0 = Checked|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x64.ActiveCfg = Checked|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x64.Build.0 = Checked|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x86.ActiveCfg = Checked|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Checked|x86.Build.0 = Checked|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm.ActiveCfg = Debug|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm.Build.0 = Debug|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm64.ActiveCfg = Debug|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|arm64.Build.0 = Debug|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x64.ActiveCfg = Debug|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x64.Build.0 = Debug|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x86.ActiveCfg = Debug|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Debug|x86.Build.0 = Debug|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm.ActiveCfg = Release|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm.Build.0 = Release|arm {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm64.ActiveCfg = Release|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|arm64.Build.0 = Release|arm64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x64.ActiveCfg = Release|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x64.Build.0 = Release|x64 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x86.ActiveCfg = Release|x86 {E4BC768B-F97D-4A8F-9391-B65DF3EB47C6}.Release|x86.Build.0 = Release|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm.ActiveCfg = Checked|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm.Build.0 = Checked|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm64.ActiveCfg = Checked|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|arm64.Build.0 = Checked|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x64.ActiveCfg = Checked|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x64.Build.0 = Checked|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x86.ActiveCfg = Checked|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Checked|x86.Build.0 = Checked|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm.ActiveCfg = Debug|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm.Build.0 = Debug|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm64.ActiveCfg = Debug|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|arm64.Build.0 = Debug|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x64.ActiveCfg = Debug|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x64.Build.0 = Debug|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x86.ActiveCfg = Debug|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Debug|x86.Build.0 = Debug|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm.ActiveCfg = Release|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm.Build.0 = Release|arm {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm64.ActiveCfg = Release|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|arm64.Build.0 = Release|arm64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x64.ActiveCfg = Release|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x64.Build.0 = Release|x64 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x86.ActiveCfg = Release|x86 {ADA691AE-4E1F-4212-97E6-51A27EFCE7E4}.Release|x86.Build.0 = Release|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm.ActiveCfg = Checked|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm.Build.0 = Checked|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm64.ActiveCfg = Checked|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|arm64.Build.0 = Checked|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x64.ActiveCfg = Checked|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x64.Build.0 = Checked|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x86.ActiveCfg = Checked|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Checked|x86.Build.0 = Checked|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm.ActiveCfg = Debug|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm.Build.0 = Debug|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm64.ActiveCfg = Debug|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|arm64.Build.0 = Debug|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x64.ActiveCfg = Debug|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x64.Build.0 = Debug|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x86.ActiveCfg = Debug|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Debug|x86.Build.0 = Debug|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm.ActiveCfg = Release|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm.Build.0 = Release|arm {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm64.ActiveCfg = Release|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|arm64.Build.0 = Release|arm64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x64.ActiveCfg = Release|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x64.Build.0 = Release|x64 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x86.ActiveCfg = Release|x86 {BAF9BBDF-0DFA-4E0D-AB3C-F07657B9EBB0}.Release|x86.Build.0 = Release|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm.ActiveCfg = Checked|arm {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm.Build.0 = Checked|arm {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm64.ActiveCfg = Checked|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|arm64.Build.0 = Checked|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x64.ActiveCfg = Checked|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x64.Build.0 = Checked|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x86.ActiveCfg = Checked|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Checked|x86.Build.0 = Checked|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm.ActiveCfg = Debug|arm {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm.Build.0 = Debug|arm {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm64.ActiveCfg = Debug|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|arm64.Build.0 = Debug|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x64.ActiveCfg = Debug|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x64.Build.0 = Debug|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x86.ActiveCfg = Debug|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Debug|x86.Build.0 = Debug|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm.ActiveCfg = Release|arm {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm.Build.0 = Release|arm {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm64.ActiveCfg = Release|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|arm64.Build.0 = Release|arm64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x64.ActiveCfg = Release|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x64.Build.0 = Release|x64 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x86.ActiveCfg = Release|x86 {6147AF1A-5054-492A-9309-FA868A184414}.Release|x86.Build.0 = Release|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm.ActiveCfg = Checked|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm.Build.0 = Checked|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm64.ActiveCfg = Checked|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|arm64.Build.0 = Checked|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x64.ActiveCfg = Checked|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x64.Build.0 = Checked|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x86.ActiveCfg = Checked|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Checked|x86.Build.0 = Checked|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm.ActiveCfg = Debug|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm.Build.0 = Debug|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm64.ActiveCfg = Debug|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|arm64.Build.0 = Debug|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x64.ActiveCfg = Debug|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x64.Build.0 = Debug|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x86.ActiveCfg = Debug|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Debug|x86.Build.0 = Debug|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm.ActiveCfg = Release|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm.Build.0 = Release|arm {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm64.ActiveCfg = Release|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|arm64.Build.0 = Release|arm64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x64.ActiveCfg = Release|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x64.Build.0 = Release|x64 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x86.ActiveCfg = Release|x86 {7498DD7C-76C1-4912-AF72-DA84E05B568F}.Release|x86.Build.0 = Release|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm.ActiveCfg = Checked|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm.Build.0 = Checked|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm64.ActiveCfg = Checked|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|arm64.Build.0 = Checked|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x64.ActiveCfg = Checked|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x64.Build.0 = Checked|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x86.ActiveCfg = Checked|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Checked|x86.Build.0 = Checked|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm.ActiveCfg = Debug|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm.Build.0 = Debug|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm64.ActiveCfg = Debug|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|arm64.Build.0 = Debug|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x64.ActiveCfg = Debug|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x64.Build.0 = Debug|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x86.ActiveCfg = Debug|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Debug|x86.Build.0 = Debug|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm.ActiveCfg = Release|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm.Build.0 = Release|arm {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm64.ActiveCfg = Release|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|arm64.Build.0 = Release|arm64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x64.ActiveCfg = Release|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x64.Build.0 = Release|x64 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x86.ActiveCfg = Release|x86 {C0245BD9-6AE2-47A5-BC41-DB6F777423AF}.Release|x86.Build.0 = Release|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm.ActiveCfg = Checked|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm.Build.0 = Checked|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm64.ActiveCfg = Checked|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|arm64.Build.0 = Checked|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x64.ActiveCfg = Checked|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x64.Build.0 = Checked|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x86.ActiveCfg = Checked|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Checked|x86.Build.0 = Checked|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm.ActiveCfg = Debug|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm.Build.0 = Debug|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm64.ActiveCfg = Debug|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|arm64.Build.0 = Debug|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x64.ActiveCfg = Debug|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x64.Build.0 = Debug|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x86.ActiveCfg = Debug|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Debug|x86.Build.0 = Debug|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm.ActiveCfg = Release|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm.Build.0 = Release|arm {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm64.ActiveCfg = Release|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|arm64.Build.0 = Release|arm64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x64.ActiveCfg = Release|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x64.Build.0 = Release|x64 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x86.ActiveCfg = Release|x86 {33CAE331-16EE-443C-A0CC-4337B94A02AD}.Release|x86.Build.0 = Release|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm.ActiveCfg = Checked|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm.Build.0 = Checked|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm64.ActiveCfg = Checked|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|arm64.Build.0 = Checked|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x64.ActiveCfg = Checked|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x64.Build.0 = Checked|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x86.ActiveCfg = Checked|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Checked|x86.Build.0 = Checked|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm.ActiveCfg = Debug|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm.Build.0 = Debug|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm64.ActiveCfg = Debug|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|arm64.Build.0 = Debug|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x64.ActiveCfg = Debug|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x64.Build.0 = Debug|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x86.ActiveCfg = Debug|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Debug|x86.Build.0 = Debug|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm.ActiveCfg = Release|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm.Build.0 = Release|arm {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm64.ActiveCfg = Release|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|arm64.Build.0 = Release|arm64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x64.ActiveCfg = Release|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x64.Build.0 = Release|x64 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x86.ActiveCfg = Release|x86 {3E43ACA2-073E-4A66-BA9C-417C5F83D430}.Release|x86.Build.0 = Release|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm.ActiveCfg = Checked|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm.Build.0 = Checked|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm64.ActiveCfg = Checked|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|arm64.Build.0 = Checked|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x64.ActiveCfg = Checked|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x64.Build.0 = Checked|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x86.ActiveCfg = Checked|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Checked|x86.Build.0 = Checked|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm.ActiveCfg = Debug|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm.Build.0 = Debug|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm64.ActiveCfg = Debug|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|arm64.Build.0 = Debug|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x64.ActiveCfg = Debug|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x64.Build.0 = Debug|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x86.ActiveCfg = Debug|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Debug|x86.Build.0 = Debug|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm.ActiveCfg = Release|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm.Build.0 = Release|arm {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm64.ActiveCfg = Release|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|arm64.Build.0 = Release|arm64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x64.ActiveCfg = Release|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x64.Build.0 = Release|x64 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x86.ActiveCfg = Release|x86 {C3371E09-E8A6-4F9E-B4CB-B1CE3F4FCC51}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {81B16D59-928B-49C1-839D-10E4747B0DC0} EndGlobalSection EndGlobal
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/jit64/opt/cse/simpleexpr4_ro_loop.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <DefineConstants>$(DefineConstants);LOOP</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="simpleexpr4.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <DefineConstants>$(DefineConstants);LOOP</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="simpleexpr4.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/mono/wasm/runtime/types/consts.d.ts
declare module "consts:*" { //Constant that will be inlined by Rollup and rollup-plugin-consts. const constant: any; export default constant; }
declare module "consts:*" { //Constant that will be inlined by Rollup and rollup-plugin-consts. const constant: any; export default constant; }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/coreclr/pal/tests/palsuite/composite/object_management/event/shared/main.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Source Code: main.c and event.c ** main.c creates process and waits for all processes to get over ** event.c creates a event and then calls threads which will contend for the event ** ** This test is for Object Management Test case for event where Object type is shareable. ** Algorithm ** o Main Process Creates OBJECT_TYPE Object ** o Create PROCESS_COUNT processes aware of the Shared Object ** ** Author: ShamitP ** ** **============================================================ */ #include <palsuite.h> #include "resulttime.h" /* Test Input Variables */ unsigned int PROCESS_COUNT = 2; unsigned int THREAD_COUNT = 20; unsigned int REPEAT_COUNT = 200; unsigned int RELATION_ID = 1001; char objectSuffix[MAX_PATH_FNAME]; struct TestStats{ DWORD operationTime; unsigned int relationId; unsigned int processCount; unsigned int threadCount; unsigned int repeatCount; char* buildNumber; }; int GetParameters( int argc, char **argv) { if( (!((argc == 5) || (argc == 6) ) )|| ((argc == 1) && !strcmp(argv[1],"/?")) || !strcmp(argv[1],"/h") || !strcmp(argv[1],"/H")) { printf("PAL -Composite Object Management event Test\n"); printf("Usage:\n"); printf("main\n\t[PROCESS_COUNT (greater than 1)] \n"); printf("\t[THREAD_COUNT (greater than 1)] \n"); printf("\t[REPEAT_COUNT (greater than 1)]\n"); printf("\t[RELATION_ID [greater than or equal to 1]\n"); printf("\t[Object Name Suffix]\n"); return -1; } PROCESS_COUNT = atoi(argv[1]); if( (PROCESS_COUNT < 1) || (PROCESS_COUNT > MAXIMUM_WAIT_OBJECTS) ) { printf("\nMain Process:Invalid PROCESS_COUNT number, Pass greater than 1 and less than PROCESS_COUNT %d\n", MAXIMUM_WAIT_OBJECTS); return -1; } THREAD_COUNT = atoi(argv[2]); if( (THREAD_COUNT < 1) || (THREAD_COUNT > MAXIMUM_WAIT_OBJECTS) ) { printf("\nInvalid THREAD_COUNT number, Pass greater than 1 and less than %d\n", MAXIMUM_WAIT_OBJECTS); return -1; } REPEAT_COUNT = atoi(argv[3]); if( REPEAT_COUNT < 1) { printf("\nMain Process:Invalid REPEAT_COUNT number, Pass greater than 1\n"); return -1; } RELATION_ID = atoi(argv[4]); if( RELATION_ID < 1) { printf("\nMain Process:Invalid RELATION_ID number, Pass greater than 1\n"); return -1; } if(argc == 6) { strncpy(objectSuffix, argv[5], MAX_PATH_FNAME-1); } return 0; } PALTEST(composite_object_management_event_shared_paltest_event_shared, "composite/object_management/event/shared/paltest_event_shared") { unsigned int i = 0; HANDLE hProcess[MAXIMUM_WAIT_OBJECTS]; HANDLE hEventHandle; STARTUPINFO si[MAXIMUM_WAIT_OBJECTS]; PROCESS_INFORMATION pi[MAXIMUM_WAIT_OBJECTS]; char lpCommandLine[MAX_LONGPATH] = ""; char ObjName[MAX_PATH_FNAME] = "SHARED_EVENT"; int returnCode = 0; DWORD processReturnCode = 0; int testReturnCode = PASS; char fileName[MAX_PATH_FNAME]; FILE *pFile = NULL; DWORD dwStartTime; struct TestStats testStats; if(0 != (PAL_Initialize(argc, argv))) { return ( FAIL ); } ZeroMemory( objectSuffix, MAX_PATH_FNAME ); if(GetParameters(argc, argv)) { Fail("Error in obtaining the parameters\n"); } if(argc == 5) { strncat(ObjName, objectSuffix, MAX_PATH_FNAME - (sizeof(ObjName) + 1) ); } /* Register the start time */ dwStartTime = GetTickCount(); testStats.relationId = RELATION_ID; testStats.processCount = PROCESS_COUNT; testStats.threadCount = THREAD_COUNT; testStats.repeatCount = REPEAT_COUNT; testStats.buildNumber = getBuildNumber(); _snprintf(fileName, MAX_PATH_FNAME, "main_event_%d_.txt", RELATION_ID); pFile = fopen(fileName, "w+"); if(pFile == NULL) { Fail("Error in opening main file for write\n"); } hEventHandle = CreateEvent( NULL, /* lpEventAttributes, inheritable to child processes*/ TRUE, /* bAutomaticReset */ TRUE, /* bInitialState */ ObjName ); if( hEventHandle == NULL) { Fail("Unable to create Event handle, returned error [%d]\n", GetLastError()); } for( i = 0; i < PROCESS_COUNT; i++ ) { ZeroMemory( lpCommandLine, MAX_PATH_FNAME ); if ( _snprintf( lpCommandLine, MAX_PATH_FNAME-1, "event %d %d %d %d %s", i, THREAD_COUNT, REPEAT_COUNT, RELATION_ID, objectSuffix) < 0 ) { Fail ("Error: Insufficient Event name string length for %s for iteration [%d]\n", ObjName, i); } /* Zero the data structure space */ ZeroMemory ( &pi[i], sizeof(pi[i]) ); ZeroMemory ( &si[i], sizeof(si[i]) ); /* Set the process flags and standard io handles */ si[i].cb = sizeof(si[i]); if(!CreateProcess( NULL, /* lpApplicationName*/ lpCommandLine, /* lpCommandLine */ NULL, /* lpProcessAttributes */ NULL, /* lpThreadAttributes */ TRUE, /* bInheritHandles */ 0, /* dwCreationFlags, */ NULL, /* lpEnvironment */ NULL, /* pCurrentDirectory */ &si[i], /* lpStartupInfo */ &pi[i] /* lpProcessInformation */ )) { Fail("Process Not created for [%d], the error code is [%d]\n", i, GetLastError()); } else { hProcess[i] = pi[i].hProcess; // Trace("Process created for [%d]\n", i); } //Create Process } returnCode = WaitForMultipleObjects( PROCESS_COUNT, hProcess, TRUE, INFINITE); if( WAIT_OBJECT_0 != returnCode ) { Trace("Wait for Object(s) @ Main thread for %d processes returned %d, and GetLastError value is %d\n", PROCESS_COUNT, returnCode, GetLastError()); testReturnCode = FAIL; } // Trace("Test over\n"); for( i = 0; i < PROCESS_COUNT; i++ ) { /* check the exit code from the process */ if( ! GetExitCodeProcess( pi[i].hProcess, &processReturnCode ) ) { Trace( "GetExitCodeProcess call failed for iteration %d with error code %u\n", i, GetLastError() ); testReturnCode = FAIL; } if(processReturnCode == FAIL) { Trace( "Process [%d] failed and returned FAIL\n", i); testReturnCode = FAIL; } if(!CloseHandle(pi[i].hThread)) { Trace("Error:%d: CloseHandle failed for Process [%d] hThread\n", GetLastError(), i); testReturnCode = FAIL; } if(!CloseHandle(pi[i].hProcess) ) { Trace("Error:%d: CloseHandle failed for Process [%d] hProcess\n", GetLastError(), i); testReturnCode = FAIL; } } testStats.operationTime = GetTimeDiff(dwStartTime); fprintf(pFile, "%d,%d,%d,%d,%d,%s\n", testStats.operationTime, testStats.relationId, testStats.processCount, testStats.threadCount, testStats.repeatCount, testStats.buildNumber); if(fclose(pFile)) { Trace("Error: fclose failed for pFile\n"); testReturnCode = FAIL; } if(!CloseHandle(hEventHandle)) { Trace("Error:%d: CloseHandle failed for hEventHandle\n", GetLastError()); testReturnCode = FAIL; } if( testReturnCode == PASS) { Trace("Test Passed\n"); } else { Trace("Test Failed\n"); } PAL_Terminate(); return testReturnCode; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Source Code: main.c and event.c ** main.c creates process and waits for all processes to get over ** event.c creates a event and then calls threads which will contend for the event ** ** This test is for Object Management Test case for event where Object type is shareable. ** Algorithm ** o Main Process Creates OBJECT_TYPE Object ** o Create PROCESS_COUNT processes aware of the Shared Object ** ** Author: ShamitP ** ** **============================================================ */ #include <palsuite.h> #include "resulttime.h" /* Test Input Variables */ unsigned int PROCESS_COUNT = 2; unsigned int THREAD_COUNT = 20; unsigned int REPEAT_COUNT = 200; unsigned int RELATION_ID = 1001; char objectSuffix[MAX_PATH_FNAME]; struct TestStats{ DWORD operationTime; unsigned int relationId; unsigned int processCount; unsigned int threadCount; unsigned int repeatCount; char* buildNumber; }; int GetParameters( int argc, char **argv) { if( (!((argc == 5) || (argc == 6) ) )|| ((argc == 1) && !strcmp(argv[1],"/?")) || !strcmp(argv[1],"/h") || !strcmp(argv[1],"/H")) { printf("PAL -Composite Object Management event Test\n"); printf("Usage:\n"); printf("main\n\t[PROCESS_COUNT (greater than 1)] \n"); printf("\t[THREAD_COUNT (greater than 1)] \n"); printf("\t[REPEAT_COUNT (greater than 1)]\n"); printf("\t[RELATION_ID [greater than or equal to 1]\n"); printf("\t[Object Name Suffix]\n"); return -1; } PROCESS_COUNT = atoi(argv[1]); if( (PROCESS_COUNT < 1) || (PROCESS_COUNT > MAXIMUM_WAIT_OBJECTS) ) { printf("\nMain Process:Invalid PROCESS_COUNT number, Pass greater than 1 and less than PROCESS_COUNT %d\n", MAXIMUM_WAIT_OBJECTS); return -1; } THREAD_COUNT = atoi(argv[2]); if( (THREAD_COUNT < 1) || (THREAD_COUNT > MAXIMUM_WAIT_OBJECTS) ) { printf("\nInvalid THREAD_COUNT number, Pass greater than 1 and less than %d\n", MAXIMUM_WAIT_OBJECTS); return -1; } REPEAT_COUNT = atoi(argv[3]); if( REPEAT_COUNT < 1) { printf("\nMain Process:Invalid REPEAT_COUNT number, Pass greater than 1\n"); return -1; } RELATION_ID = atoi(argv[4]); if( RELATION_ID < 1) { printf("\nMain Process:Invalid RELATION_ID number, Pass greater than 1\n"); return -1; } if(argc == 6) { strncpy(objectSuffix, argv[5], MAX_PATH_FNAME-1); } return 0; } PALTEST(composite_object_management_event_shared_paltest_event_shared, "composite/object_management/event/shared/paltest_event_shared") { unsigned int i = 0; HANDLE hProcess[MAXIMUM_WAIT_OBJECTS]; HANDLE hEventHandle; STARTUPINFO si[MAXIMUM_WAIT_OBJECTS]; PROCESS_INFORMATION pi[MAXIMUM_WAIT_OBJECTS]; char lpCommandLine[MAX_LONGPATH] = ""; char ObjName[MAX_PATH_FNAME] = "SHARED_EVENT"; int returnCode = 0; DWORD processReturnCode = 0; int testReturnCode = PASS; char fileName[MAX_PATH_FNAME]; FILE *pFile = NULL; DWORD dwStartTime; struct TestStats testStats; if(0 != (PAL_Initialize(argc, argv))) { return ( FAIL ); } ZeroMemory( objectSuffix, MAX_PATH_FNAME ); if(GetParameters(argc, argv)) { Fail("Error in obtaining the parameters\n"); } if(argc == 5) { strncat(ObjName, objectSuffix, MAX_PATH_FNAME - (sizeof(ObjName) + 1) ); } /* Register the start time */ dwStartTime = GetTickCount(); testStats.relationId = RELATION_ID; testStats.processCount = PROCESS_COUNT; testStats.threadCount = THREAD_COUNT; testStats.repeatCount = REPEAT_COUNT; testStats.buildNumber = getBuildNumber(); _snprintf(fileName, MAX_PATH_FNAME, "main_event_%d_.txt", RELATION_ID); pFile = fopen(fileName, "w+"); if(pFile == NULL) { Fail("Error in opening main file for write\n"); } hEventHandle = CreateEvent( NULL, /* lpEventAttributes, inheritable to child processes*/ TRUE, /* bAutomaticReset */ TRUE, /* bInitialState */ ObjName ); if( hEventHandle == NULL) { Fail("Unable to create Event handle, returned error [%d]\n", GetLastError()); } for( i = 0; i < PROCESS_COUNT; i++ ) { ZeroMemory( lpCommandLine, MAX_PATH_FNAME ); if ( _snprintf( lpCommandLine, MAX_PATH_FNAME-1, "event %d %d %d %d %s", i, THREAD_COUNT, REPEAT_COUNT, RELATION_ID, objectSuffix) < 0 ) { Fail ("Error: Insufficient Event name string length for %s for iteration [%d]\n", ObjName, i); } /* Zero the data structure space */ ZeroMemory ( &pi[i], sizeof(pi[i]) ); ZeroMemory ( &si[i], sizeof(si[i]) ); /* Set the process flags and standard io handles */ si[i].cb = sizeof(si[i]); if(!CreateProcess( NULL, /* lpApplicationName*/ lpCommandLine, /* lpCommandLine */ NULL, /* lpProcessAttributes */ NULL, /* lpThreadAttributes */ TRUE, /* bInheritHandles */ 0, /* dwCreationFlags, */ NULL, /* lpEnvironment */ NULL, /* pCurrentDirectory */ &si[i], /* lpStartupInfo */ &pi[i] /* lpProcessInformation */ )) { Fail("Process Not created for [%d], the error code is [%d]\n", i, GetLastError()); } else { hProcess[i] = pi[i].hProcess; // Trace("Process created for [%d]\n", i); } //Create Process } returnCode = WaitForMultipleObjects( PROCESS_COUNT, hProcess, TRUE, INFINITE); if( WAIT_OBJECT_0 != returnCode ) { Trace("Wait for Object(s) @ Main thread for %d processes returned %d, and GetLastError value is %d\n", PROCESS_COUNT, returnCode, GetLastError()); testReturnCode = FAIL; } // Trace("Test over\n"); for( i = 0; i < PROCESS_COUNT; i++ ) { /* check the exit code from the process */ if( ! GetExitCodeProcess( pi[i].hProcess, &processReturnCode ) ) { Trace( "GetExitCodeProcess call failed for iteration %d with error code %u\n", i, GetLastError() ); testReturnCode = FAIL; } if(processReturnCode == FAIL) { Trace( "Process [%d] failed and returned FAIL\n", i); testReturnCode = FAIL; } if(!CloseHandle(pi[i].hThread)) { Trace("Error:%d: CloseHandle failed for Process [%d] hThread\n", GetLastError(), i); testReturnCode = FAIL; } if(!CloseHandle(pi[i].hProcess) ) { Trace("Error:%d: CloseHandle failed for Process [%d] hProcess\n", GetLastError(), i); testReturnCode = FAIL; } } testStats.operationTime = GetTimeDiff(dwStartTime); fprintf(pFile, "%d,%d,%d,%d,%d,%s\n", testStats.operationTime, testStats.relationId, testStats.processCount, testStats.threadCount, testStats.repeatCount, testStats.buildNumber); if(fclose(pFile)) { Trace("Error: fclose failed for pFile\n"); testReturnCode = FAIL; } if(!CloseHandle(hEventHandle)) { Trace("Error:%d: CloseHandle failed for hEventHandle\n", GetLastError()); testReturnCode = FAIL; } if( testReturnCode == PASS) { Trace("Test Passed\n"); } else { Trace("Test Failed\n"); } PAL_Terminate(); return testReturnCode; }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/contains-email.xml
<!-- Description: name containing an email address produces a warning Expect: ContainsEmail{element:name,parent:author} --> <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 &lt;[email protected]&gt;</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>Some text.</summary> </entry> </feed>
<!-- Description: name containing an email address produces a warning Expect: ContainsEmail{element:name,parent:author} --> <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 &lt;[email protected]&gt;</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>Some text.</summary> </entry> </feed>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/MultiplyDoublingWideningSaturateScalarBySelectedScalar.Vector64.Int32.Vector128.Int32.3.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 MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); 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__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); 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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly byte Imm = 3; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( _clsVar1, _clsVar2, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(test._fld1, test._fld2, 3); 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__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, Vector128<Int32> secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.MultiplyDoublingWideningSaturate(firstOp[0], secondOp[Imm]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar)}<Int64>(Vector64<Int32>, Vector128<Int32>, 3): {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 MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); 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__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); 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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly byte Imm = 3; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( _clsVar1, _clsVar2, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(test._fld1, test._fld2, 3); 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__MultiplyDoublingWideningSaturateScalarBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, Vector128<Int32> secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.MultiplyDoublingWideningSaturate(firstOp[0], secondOp[Imm]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MultiplyDoublingWideningSaturateScalarBySelectedScalar)}<Int64>(Vector64<Int32>, Vector128<Int32>, 3): {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,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/authorless-with-no-entries.xml
<!-- Description: a feed with two atom:entry elements with the same atom:id and same atom:updated values produces a warning. Expect: !MissingElement{parent:feed,element:author} --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> </feed>
<!-- Description: a feed with two atom:entry elements with the same atom:id and same atom:updated values produces a warning. Expect: !MissingElement{parent:feed,element:author} --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> </feed>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/Loader/classloader/generics/Instantiation/Negative/param07.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 System.Console { } .assembly extern xunit.core {} // Microsoft (R) .NET Framework IL Disassembler. Version 1.1.2019.0 // Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. // Metadata version: v1.1.2019 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .hash = (73 26 79 1F 31 96 69 CE 57 B9 48 24 EE A8 34 F1 // s&y.1.i.W.H$..4. 42 87 88 29 ) // B..) .ver 1:1:3300:0 } .assembly 'param07' { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(bool, // bool) = ( 01 00 00 01 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } // MVID: {A165307B-2178-469D-A064-956E56145B09} .imagebase 0x00400000 .subsystem 0x00000003 .file alignment 512 .corflags 0x00000001 // Image base: 0x034B0000 // =============== CLASS MEMBERS DECLARATION =================== .class public sequential ansi sealed beforefieldinit Gen<([mscorlib]System.Object) T> extends [mscorlib]System.ValueType { .pack 0 .size 1 .method public hidebysig instance void Dummy() cil managed { // Code size 1 (0x1) .maxstack 0 IL_0000: ret } // end of method Gen::Dummy } // end of class Gen .class public auto ansi beforefieldinit GenTest<([mscorlib]System.Object) T> extends [mscorlib]System.Object { .method private hidebysig instance void InternalTest() cil managed { // Code size 18 (0x12) .maxstack 1 .locals init (valuetype Gen<!0> V_0) IL_0000: ldloca.s V_0 IL_0002: initobj valuetype Gen<!0> IL_0008: ldloc.0 IL_0009: stloc.0 IL_000a: ldloca.s V_0 IL_000c: call instance void valuetype Gen::Dummy() IL_0011: ret } // end of method GenTest::InternalTest .method private hidebysig instance void IndirectTest() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void class GenTest<!0>::InternalTest() IL_0006: ret } // end of method GenTest::IndirectTest .method public hidebysig instance bool Test_param07() cil managed { // Code size 48 (0x30) .maxstack 2 .locals init (class [mscorlib]System.Exception V_0, bool V_1) .try { IL_0000: ldarg.0 IL_0001: call instance void class GenTest<!0>::IndirectTest() IL_0006: ldstr "Test did not throw expected System.TypeLoadException" IL_000b: call void [System.Console]System.Console::WriteLine(string) IL_0010: ldc.i4.0 IL_0011: stloc.1 IL_0012: leave.s IL_002e } // end .try catch [mscorlib]System.TypeLoadException { IL_0014: pop IL_0015: ldc.i4.1 IL_0016: stloc.1 IL_0017: leave.s IL_002e } // end handler catch [mscorlib]System.Exception { IL_0019: stloc.0 IL_001a: ldstr "Test caught unexpected Exception " IL_001f: ldloc.0 IL_0020: call string [mscorlib]System.String::Concat(object, object) IL_0025: call void [System.Console]System.Console::WriteLine(string) IL_002a: ldc.i4.0 IL_002b: stloc.1 IL_002c: leave.s IL_002e } // end handler IL_002e: ldloc.1 IL_002f: ret } // end of method GenTest::Test .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method GenTest::.ctor } // end of class GenTest .class public auto ansi beforefieldinit Test_param07 extends [mscorlib]System.Object { .field public static int32 counter .field public static bool result .method public hidebysig static void Eval(bool exp) cil managed { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld int32 Test_param07::counter IL_0005: ldc.i4.1 IL_0006: add IL_0007: stsfld int32 Test_param07::counter IL_000c: ldarg.0 IL_000d: brtrue.s IL_002e IL_000f: ldarg.0 IL_0010: stsfld bool Test_param07::result IL_0015: ldstr "Test Failed at location: " IL_001a: ldsfld int32 Test_param07::counter IL_001f: box [mscorlib]System.Int32 IL_0024: call string [mscorlib]System.String::Concat(object, object) IL_0029: call void [System.Console]System.Console::WriteLine(string) IL_002e: ret } // end of method Test::Eval .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 113 (0x71) .maxstack 1 .locals init (int32 V_0) IL_0000: newobj instance void class GenTest<int32>::.ctor() IL_0005: call instance bool class GenTest<int32>::Test_param07() IL_000a: call void Test_param07::Eval(bool) IL_000f: newobj instance void class GenTest<float64>::.ctor() IL_0014: call instance bool class GenTest<float64>::Test_param07() IL_0019: call void Test_param07::Eval(bool) IL_001e: newobj instance void class GenTest<valuetype [mscorlib]System.Guid>::.ctor() IL_0023: call instance bool class GenTest<valuetype [mscorlib]System.Guid>::Test_param07() IL_0028: call void Test_param07::Eval(bool) IL_002d: newobj instance void class GenTest<string>::.ctor() IL_0032: call instance bool class GenTest<string>::Test_param07() IL_0037: call void Test_param07::Eval(bool) IL_003c: newobj instance void class GenTest<object>::.ctor() IL_0041: call instance bool class GenTest<object>::Test_param07() IL_0046: call void Test_param07::Eval(bool) IL_004b: ldsfld bool Test_param07::result IL_0050: brfalse.s IL_0061 IL_0052: ldstr "Test Passed" IL_0057: call void [System.Console]System.Console::WriteLine(string) IL_005c: ldc.i4.s 100 IL_005e: stloc.0 IL_005f: br.s IL_006f IL_0061: ldstr "Test Failed" IL_0066: call void [System.Console]System.Console::WriteLine(string) IL_006b: ldc.i4.1 IL_006c: stloc.0 IL_006d: br.s IL_006f IL_006f: ldloc.0 IL_0070: ret } // end of method Test::Main .method private hidebysig specialname rtspecialname static void .cctor() cil managed { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: stsfld int32 Test_param07::counter IL_0006: ldc.i4.1 IL_0007: stsfld bool Test_param07::result IL_000c: ret } // end of method Test::.cctor .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test::.ctor } // end of class Test // ============================================================= //*********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file param07.res
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern System.Console { } .assembly extern xunit.core {} // Microsoft (R) .NET Framework IL Disassembler. Version 1.1.2019.0 // Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. // Metadata version: v1.1.2019 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .hash = (73 26 79 1F 31 96 69 CE 57 B9 48 24 EE A8 34 F1 // s&y.1.i.W.H$..4. 42 87 88 29 ) // B..) .ver 1:1:3300:0 } .assembly 'param07' { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(bool, // bool) = ( 01 00 00 01 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } // MVID: {A165307B-2178-469D-A064-956E56145B09} .imagebase 0x00400000 .subsystem 0x00000003 .file alignment 512 .corflags 0x00000001 // Image base: 0x034B0000 // =============== CLASS MEMBERS DECLARATION =================== .class public sequential ansi sealed beforefieldinit Gen<([mscorlib]System.Object) T> extends [mscorlib]System.ValueType { .pack 0 .size 1 .method public hidebysig instance void Dummy() cil managed { // Code size 1 (0x1) .maxstack 0 IL_0000: ret } // end of method Gen::Dummy } // end of class Gen .class public auto ansi beforefieldinit GenTest<([mscorlib]System.Object) T> extends [mscorlib]System.Object { .method private hidebysig instance void InternalTest() cil managed { // Code size 18 (0x12) .maxstack 1 .locals init (valuetype Gen<!0> V_0) IL_0000: ldloca.s V_0 IL_0002: initobj valuetype Gen<!0> IL_0008: ldloc.0 IL_0009: stloc.0 IL_000a: ldloca.s V_0 IL_000c: call instance void valuetype Gen::Dummy() IL_0011: ret } // end of method GenTest::InternalTest .method private hidebysig instance void IndirectTest() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void class GenTest<!0>::InternalTest() IL_0006: ret } // end of method GenTest::IndirectTest .method public hidebysig instance bool Test_param07() cil managed { // Code size 48 (0x30) .maxstack 2 .locals init (class [mscorlib]System.Exception V_0, bool V_1) .try { IL_0000: ldarg.0 IL_0001: call instance void class GenTest<!0>::IndirectTest() IL_0006: ldstr "Test did not throw expected System.TypeLoadException" IL_000b: call void [System.Console]System.Console::WriteLine(string) IL_0010: ldc.i4.0 IL_0011: stloc.1 IL_0012: leave.s IL_002e } // end .try catch [mscorlib]System.TypeLoadException { IL_0014: pop IL_0015: ldc.i4.1 IL_0016: stloc.1 IL_0017: leave.s IL_002e } // end handler catch [mscorlib]System.Exception { IL_0019: stloc.0 IL_001a: ldstr "Test caught unexpected Exception " IL_001f: ldloc.0 IL_0020: call string [mscorlib]System.String::Concat(object, object) IL_0025: call void [System.Console]System.Console::WriteLine(string) IL_002a: ldc.i4.0 IL_002b: stloc.1 IL_002c: leave.s IL_002e } // end handler IL_002e: ldloc.1 IL_002f: ret } // end of method GenTest::Test .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method GenTest::.ctor } // end of class GenTest .class public auto ansi beforefieldinit Test_param07 extends [mscorlib]System.Object { .field public static int32 counter .field public static bool result .method public hidebysig static void Eval(bool exp) cil managed { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld int32 Test_param07::counter IL_0005: ldc.i4.1 IL_0006: add IL_0007: stsfld int32 Test_param07::counter IL_000c: ldarg.0 IL_000d: brtrue.s IL_002e IL_000f: ldarg.0 IL_0010: stsfld bool Test_param07::result IL_0015: ldstr "Test Failed at location: " IL_001a: ldsfld int32 Test_param07::counter IL_001f: box [mscorlib]System.Int32 IL_0024: call string [mscorlib]System.String::Concat(object, object) IL_0029: call void [System.Console]System.Console::WriteLine(string) IL_002e: ret } // end of method Test::Eval .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 113 (0x71) .maxstack 1 .locals init (int32 V_0) IL_0000: newobj instance void class GenTest<int32>::.ctor() IL_0005: call instance bool class GenTest<int32>::Test_param07() IL_000a: call void Test_param07::Eval(bool) IL_000f: newobj instance void class GenTest<float64>::.ctor() IL_0014: call instance bool class GenTest<float64>::Test_param07() IL_0019: call void Test_param07::Eval(bool) IL_001e: newobj instance void class GenTest<valuetype [mscorlib]System.Guid>::.ctor() IL_0023: call instance bool class GenTest<valuetype [mscorlib]System.Guid>::Test_param07() IL_0028: call void Test_param07::Eval(bool) IL_002d: newobj instance void class GenTest<string>::.ctor() IL_0032: call instance bool class GenTest<string>::Test_param07() IL_0037: call void Test_param07::Eval(bool) IL_003c: newobj instance void class GenTest<object>::.ctor() IL_0041: call instance bool class GenTest<object>::Test_param07() IL_0046: call void Test_param07::Eval(bool) IL_004b: ldsfld bool Test_param07::result IL_0050: brfalse.s IL_0061 IL_0052: ldstr "Test Passed" IL_0057: call void [System.Console]System.Console::WriteLine(string) IL_005c: ldc.i4.s 100 IL_005e: stloc.0 IL_005f: br.s IL_006f IL_0061: ldstr "Test Failed" IL_0066: call void [System.Console]System.Console::WriteLine(string) IL_006b: ldc.i4.1 IL_006c: stloc.0 IL_006d: br.s IL_006f IL_006f: ldloc.0 IL_0070: ret } // end of method Test::Main .method private hidebysig specialname rtspecialname static void .cctor() cil managed { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: stsfld int32 Test_param07::counter IL_0006: ldc.i4.1 IL_0007: stsfld bool Test_param07::result IL_000c: ret } // end of method Test::.cctor .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test::.ctor } // end of class Test // ============================================================= //*********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file param07.res
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/bug264908_v2.xsd
<xs:schema xmlns:xml="http://www.w3.org/XML/1998/namespace" targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:include schemaLocation="bug264908_v2a.xsd" /> <xs:attribute name="lang" type="xs:language" /> <xs:attribute name="base" type="xs:anyURI" /> <xs:attribute default="preserve" name="space"> <xs:simpleType> <xs:restriction base="xs:NCName"> <xs:enumeration value="default" /> <xs:enumeration value="preserve" /> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="blah"/> <xs:attributeGroup name="specialAttrs"> <xs:attribute ref="xml:lang" /> <xs:attribute ref="xml:space" /> <xs:attribute ref="xml:base" /> <xs:attribute ref="xml:blah" /> </xs:attributeGroup> </xs:schema>
<xs:schema xmlns:xml="http://www.w3.org/XML/1998/namespace" targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:include schemaLocation="bug264908_v2a.xsd" /> <xs:attribute name="lang" type="xs:language" /> <xs:attribute name="base" type="xs:anyURI" /> <xs:attribute default="preserve" name="space"> <xs:simpleType> <xs:restriction base="xs:NCName"> <xs:enumeration value="default" /> <xs:enumeration value="preserve" /> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="blah"/> <xs:attributeGroup name="specialAttrs"> <xs:attribute ref="xml:lang" /> <xs:attribute ref="xml:space" /> <xs:attribute ref="xml:base" /> <xs:attribute ref="xml:blah" /> </xs:attributeGroup> </xs:schema>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/AddParameterFB4.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" omit-xml-declaration="yes" /> <xsl:variable name="param1" select="'default global'"/> <xsl:template match="/"> <xsl:call-template name="Test"> <xsl:with-param name="param1" select="'with-param'" /> </xsl:call-template> </xsl:template> <xsl:template name="Test"> <xsl:variable name="param1" select="'default local'" /> <result><xsl:value-of select="$param1" /></result> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" omit-xml-declaration="yes" /> <xsl:variable name="param1" select="'default global'"/> <xsl:template match="/"> <xsl:call-template name="Test"> <xsl:with-param name="param1" select="'with-param'" /> </xsl:call-template> </xsl:template> <xsl:template name="Test"> <xsl:variable name="param1" select="'default local'" /> <result><xsl:value-of select="$param1" /></result> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Common/tests/System/Net/Http/HttpClientHandlerTest.Proxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Net.Http.Headers; using System.Net.Sockets; using System.Net.Test.Common; using System.Text; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Microsoft.DotNet.RemoteExecutor; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; #if WINHTTPHANDLER_TEST using HttpClientHandler = System.Net.Http.WinHttpClientHandler; #endif public abstract class HttpClientHandler_Proxy_Test : HttpClientHandlerTestBase { public HttpClientHandler_Proxy_Test(ITestOutputHelper output) : base(output) { } [Fact] public async Task Dispose_HandlerWithProxy_ProxyNotDisposed() { if (IsWinHttpHandler && UseVersion >= HttpVersion20.Value) { return; } var proxy = new TrackDisposalProxy(); await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClientHandler handler = CreateHttpClientHandler()) { handler.UseProxy = true; handler.Proxy = proxy; using (HttpClient client = CreateHttpClient(handler)) { Assert.Equal("hello", await client.GetStringAsync(uri)); } } }, async server => { await server.HandleRequestAsync(content: "hello"); }); Assert.True(proxy.ProxyUsed); Assert.False(proxy.Disposed); } [ActiveIssue("https://github.com/dotnet/runtime/issues/1507")] [OuterLoop("Uses external servers")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] [InlineData(AuthenticationSchemes.Ntlm, true, false)] [InlineData(AuthenticationSchemes.Negotiate, true, false)] [InlineData(AuthenticationSchemes.Basic, false, false)] [InlineData(AuthenticationSchemes.Basic, true, false)] [InlineData(AuthenticationSchemes.Digest, false, false)] [InlineData(AuthenticationSchemes.Digest, true, false)] [InlineData(AuthenticationSchemes.Ntlm, false, false)] [InlineData(AuthenticationSchemes.Negotiate, false, false)] [InlineData(AuthenticationSchemes.Basic, false, true)] [InlineData(AuthenticationSchemes.Basic, true, true)] [InlineData(AuthenticationSchemes.Digest, false, true)] [InlineData(AuthenticationSchemes.Digest, true, true)] public async Task AuthProxy__ValidCreds_ProxySendsRequestToServer( AuthenticationSchemes proxyAuthScheme, bool secureServer, bool proxyClosesConnectionAfterFirst407Response) { if (!PlatformDetection.IsWindows && (proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm)) { // CI machines don't have GSSAPI module installed and will fail with error from // System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle(): // "GSSAPI operation failed with error - An invalid status code was supplied // Configuration file does not specify default realm)." return; } Uri serverUri = secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer; var options = new LoopbackProxyServer.Options { AuthenticationSchemes = proxyAuthScheme, ConnectionCloseAfter407 = proxyClosesConnectionAfterFirst407Response }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyServer.Uri); handler.Proxy.Credentials = new NetworkCredential("username", "password"); using (HttpResponseMessage response = await client.GetAsync(serverUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } } } public static bool IsSocketsHttpHandlerAndRemoteExecutorSupported => !HttpClientHandlerTestBase.IsWinHttpHandler && RemoteExecutor.IsSupported; [OuterLoop("Uses external servers")] [ConditionalFact(nameof(IsSocketsHttpHandlerAndRemoteExecutorSupported))] public void Proxy_UseEnvironmentVariableToSetSystemProxy_RequestGoesThruProxy() { RemoteExecutor.Invoke(async (useVersionString) => { var options = new LoopbackProxyServer.Options { AddViaRequestHeader = true }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { Environment.SetEnvironmentVariable("http_proxy", proxyServer.Uri.AbsoluteUri.ToString()); using (HttpClient client = CreateHttpClient(useVersionString)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string body = await response.Content.ReadAsStringAsync(); Assert.Contains(proxyServer.ViaHeader, body); } } }, UseVersion.ToString()).Dispose(); } const string BasicAuth = "Basic"; const string content = "This is a test"; private static ICredentials ConstructCredentials(NetworkCredential cred, Uri uriPrefix, string authType, bool wrapCredsInCache) { if (wrapCredsInCache) { var cache = new CredentialCache(); cache.Add(uriPrefix, authType, cred); return cache; } return cred; } private void ValidateProxyBasicAuthentication(LoopbackProxyServer proxyServer, NetworkCredential cred) { if (cred != null) { string expectedAuth = string.IsNullOrEmpty(cred.Domain) ? $"{cred.UserName}:{cred.Password}" : $"{cred.Domain}\\{cred.UserName}:{cred.Password}"; _output.WriteLine($"expectedAuth={expectedAuth}"); string expectedAuthHash = Convert.ToBase64String(Encoding.UTF8.GetBytes(expectedAuth)); // Check last request to proxy server. Handlers that don't use // pre-auth for proxy will make 2 requests. int requestCount = proxyServer.Requests.Count; _output.WriteLine($"proxyServer.Requests.Count={requestCount}"); Assert.Equal(BasicAuth, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueScheme); Assert.Equal(expectedAuthHash, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueToken); } } [OuterLoop("Uses external servers")] [Theory] [MemberData(nameof(CredentialsForProxy))] public async Task AuthenticatedProxiedRequest_GetAsyncWithCreds_Success(NetworkCredential cred, bool wrapCredsInCache, bool connectionCloseAfter407) { var options = new LoopbackProxyServer.Options { AuthenticationSchemes = cred != null ? AuthenticationSchemes.Basic : AuthenticationSchemes.None, ConnectionCloseAfter407 = connectionCloseAfter407 }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = ConstructCredentials(cred, proxyServer.Uri, BasicAuth, wrapCredsInCache) }; using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); ValidateProxyBasicAuthentication(proxyServer, cred); } } } [OuterLoop("Uses external servers")] [Theory] [MemberData(nameof(CredentialsForProxy))] public async Task AuthenticatedProxyTunnelRequest_PostAsyncWithCreds_Success(NetworkCredential cred, bool wrapCredsInCache, bool connectionCloseAfter407) { if (IsWinHttpHandler) { return; } var options = new LoopbackProxyServer.Options { AuthenticationSchemes = cred != null ? AuthenticationSchemes.Basic : AuthenticationSchemes.None, ConnectionCloseAfter407 = connectionCloseAfter407 }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = ConstructCredentials(cred, proxyServer.Uri, BasicAuth, wrapCredsInCache) }; using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, new StringContent(content))) { string responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, content); ValidateProxyBasicAuthentication(proxyServer, cred); } } } [OuterLoop("Uses external servers")] [Theory] [MemberData(nameof(BypassedProxies))] public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = proxy; using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [OuterLoop("Uses external servers")] [Fact] public async Task AuthenticatedProxiedRequest_GetAsyncWithNoCreds_ProxyAuthenticationRequiredStatusCode() { var options = new LoopbackProxyServer.Options { AuthenticationSchemes = AuthenticationSchemes.Basic }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } } } [Fact] public async Task AuthenticatedProxyTunnelRequest_PostAsyncWithNoCreds_Throws() { if (IsWinHttpHandler) { return; } var options = new LoopbackProxyServer.Options { AuthenticationSchemes = AuthenticationSchemes.Basic, }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; using (HttpClient client = CreateHttpClient(handler)) { HttpRequestException e = await Assert.ThrowsAnyAsync<HttpRequestException>(async () => await client.PostAsync("https://nosuchhost.invalid", new StringContent(content))); Assert.Contains("407", e.Message); } } } [Fact] public async Task Proxy_SslProxyUnsupported_Throws() { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy("https://" + Guid.NewGuid().ToString("N")); Type expectedType = IsWinHttpHandler ? typeof(HttpRequestException) : typeof(NotSupportedException); await Assert.ThrowsAsync(expectedType, () => client.GetAsync("http://" + Guid.NewGuid().ToString("N"))); } } [Fact] public async Task ProxyTunnelRequest_GetAsync_Success() { if (IsWinHttpHandler) { return; } const string Content = "Hello world"; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create()) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; using (HttpClient client = CreateHttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server, uri) => { Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri)); Task<HttpResponseMessage> clientTask = client.GetAsync(uri); await server.AcceptConnectionSendResponseAndCloseAsync(content: Content); using (var response = await clientTask) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Content, await response.Content.ReadAsStringAsync()); } }, options); } Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine); } } [Fact] public async Task ProxyTunnelRequest_MaxConnectionsSetButDoesNotApplyToProxyConnect_Success() { if (IsWinHttpHandler) { return; } const string Content = "Hello world"; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create()) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; handler.MaxConnectionsPerServer = 1; using (HttpClient client = CreateHttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server1, uri1) => { await LoopbackServer.CreateServerAsync(async (server2, uri2) => { Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri1)); Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri2)); Task<HttpResponseMessage> clientTask1 = client.GetAsync(uri1); Task<HttpResponseMessage> clientTask2 = client.GetAsync(uri2); await server1.AcceptConnectionAsync(async connection1 => { await server2.AcceptConnectionAsync(async connection2 => { await connection1.HandleRequestAsync(content: Content); await connection2.HandleRequestAsync(content: Content); }); }); using (var response1 = await clientTask1) { Assert.Equal(HttpStatusCode.OK, response1.StatusCode); Assert.Equal(Content, await response1.Content.ReadAsStringAsync()); } using (var response2 = await clientTask2) { Assert.Equal(HttpStatusCode.OK, response2.StatusCode); Assert.Equal(Content, await response2.Content.ReadAsStringAsync()); } }, options); }, options); } Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine); Assert.Contains("CONNECT", proxyServer.Requests[1].RequestLine); } } [Fact] public async Task ProxyTunnelRequest_OriginServerSendsProxyAuthChallenge_NoProxyAuthPerformed() { if (IsWinHttpHandler) { return; } using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create()) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = ConstructCredentials(new NetworkCredential("username", "password"), proxyServer.Uri, BasicAuth, true) }; handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; using (HttpClient client = CreateHttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server, uri) => { Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri)); Task<HttpResponseMessage> clientTask = client.GetAsync(uri); await server.AcceptConnectionSendResponseAndCloseAsync(statusCode: HttpStatusCode.ProxyAuthenticationRequired, additionalHeaders: "Proxy-Authenticate: Basic"); using (var response = await clientTask) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } }, options); } Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public async Task ProxyAuth_Digest_Succeeds() { const string expectedUsername = "user"; const string expectedPassword = "password"; const string authHeader = "Proxy-Authenticate: Digest realm=\"NetCore\", nonce=\"PwOnWgAAAAAAjnbW438AAJSQi1kAAAAA\", qop=\"auth\", stale=false\r\n"; LoopbackServer.Options options = new LoopbackServer.Options { IsProxy = true, Username = expectedUsername, Password = expectedPassword }; var proxyCreds = new NetworkCredential(expectedUsername, expectedPassword); await LoopbackServer.CreateServerAsync(async (proxyServer, proxyUrl) => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUrl) { Credentials = proxyCreds }; // URL does not matter. We will get response from "proxy" code below. Task<HttpResponseMessage> clientTask = client.GetAsync($"http://notarealserver.com/"); // Send Digest challenge. Task<List<string>> serverTask = proxyServer.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.ProxyAuthenticationRequired, authHeader); if (clientTask == await Task.WhenAny(clientTask, serverTask).WaitAsync(TestHelper.PassingTestTimeout)) { // Client task shouldn't have completed successfully; propagate failure. Assert.NotEqual(TaskStatus.RanToCompletion, clientTask.Status); await clientTask; } // Verify user & password. serverTask = proxyServer.AcceptConnectionPerformAuthenticationAndCloseAsync(""); await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { clientTask, serverTask }, TestHelper.PassingTestTimeoutMilliseconds); Assert.Equal(HttpStatusCode.OK, clientTask.Result.StatusCode); } }, options); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public async Task MultiProxy_PAC_Failover_Succeeds() { if (IsWinHttpHandler) { // PAC-based failover is only supported on Windows/SocketsHttpHandler return; } // Create our failing proxy server. // Bind a port to reserve it, but don't start listening yet. The first Connect() should fail and cause a fail-over. using Socket failingProxyServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); failingProxyServer.Bind(new IPEndPoint(IPAddress.Loopback, 0)); var failingEndPoint = (IPEndPoint)failingProxyServer.LocalEndPoint; using LoopbackProxyServer succeedingProxyServer = LoopbackProxyServer.Create(); string proxyConfigString = $"{failingEndPoint.Address}:{failingEndPoint.Port} {succeedingProxyServer.Uri.Host}:{succeedingProxyServer.Uri.Port}"; // Create a WinInetProxyHelper and override its values with our own. object winInetProxyHelper = Activator.CreateInstance(typeof(HttpClient).Assembly.GetType("System.Net.Http.WinInetProxyHelper", true), true); winInetProxyHelper.GetType().GetField("_autoConfigUrl", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, null); winInetProxyHelper.GetType().GetField("_autoDetect", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, false); winInetProxyHelper.GetType().GetField("_proxy", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, proxyConfigString); winInetProxyHelper.GetType().GetField("_proxyBypass", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, null); // Create a HttpWindowsProxy with our custom WinInetProxyHelper. IWebProxy httpWindowsProxy = (IWebProxy)Activator.CreateInstance(typeof(HttpClient).Assembly.GetType("System.Net.Http.HttpWindowsProxy", true), Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance, null, new[] { winInetProxyHelper, null }, null); Task<bool> nextFailedConnection = null; // Run a request with that proxy. Task requestTask = LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using HttpClientHandler handler = CreateHttpClientHandler(); using HttpClient client = CreateHttpClient(handler); handler.Proxy = httpWindowsProxy; // First request is expected to hit the failing proxy server, then failover to the succeeding proxy server. Assert.Equal("foo", await client.GetStringAsync(uri)); // Second request should start directly at the succeeding proxy server. // So, start listening on our failing proxy server to catch if it tries to connect. failingProxyServer.Listen(1); nextFailedConnection = WaitForNextFailedConnection(); Assert.Equal("bar", await client.GetStringAsync(uri)); }, async server => { await server.HandleRequestAsync(statusCode: HttpStatusCode.OK, content: "foo"); await server.HandleRequestAsync(statusCode: HttpStatusCode.OK, content: "bar"); }); // Wait for request to finish. await requestTask; // Triggers WaitForNextFailedConnection to stop, and then check // to ensure we haven't got any further requests against it. failingProxyServer.Dispose(); Assert.False(await nextFailedConnection); Assert.Equal(2, succeedingProxyServer.Requests.Count); async Task<bool> WaitForNextFailedConnection() { try { (await failingProxyServer.AcceptAsync()).Dispose(); return true; } catch (SocketException ex) when (ex.SocketErrorCode == SocketError.OperationAborted) { // Dispose() of the loopback server will cause AcceptAsync() in EstablishConnectionAsync() to abort. return false; } } } [Theory] [InlineData("1.2.3.4")] [InlineData("1.2.3.4:8080")] [InlineData("[::1234]")] [InlineData("[::1234]:8080")] public async Task ProxiedIPAddressRequest_NotDefaultPort_CorrectlyFormatted(string host) { string uri = "http://" + host; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(uri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"GET {uri}/ HTTP/1.1", headers); })); Assert.True(connectionAccepted); } public static IEnumerable<object[]> DestinationHost_MemberData() { yield return new object[] { "nosuchhost.invalid" }; yield return new object[] { "1.2.3.4" }; yield return new object[] { "[::1234]" }; } [Theory] [MemberData(nameof(DestinationHost_MemberData))] public async Task ProxiedRequest_DefaultPort_PortStrippedOffInUri(string host) { string addressUri = $"http://{host}:80/"; string expectedAddressUri = $"http://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"GET {expectedAddressUri} HTTP/1.1", headers); })); Assert.True(connectionAccepted); } [Theory] [MemberData(nameof(DestinationHost_MemberData))] public async Task ProxyTunnelRequest_PortSpecified_NotStrippedOffInUri(string host) { // Https proxy request will use CONNECT tunnel, even the default 443 port is specified, it will not be stripped off. string requestTarget = $"{host}:443"; string addressUri = $"https://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"CONNECT {requestTarget} HTTP/1.1", headers); })); Assert.True(connectionAccepted); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ProxyTunnelRequest_UserAgentHeaderAdded(bool addUserAgentHeader) { if (IsWinHttpHandler) { return; // Skip test since the fix is only in SocketsHttpHandler. } string host = "nosuchhost.invalid"; string addressUri = $"https://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; if (addUserAgentHeader) { client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mozilla", "5.0")); } try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"CONNECT {host}:443 HTTP/1.1", headers); if (addUserAgentHeader) { Assert.Contains("User-Agent: Mozilla/5.0", headers); } else { Assert.DoesNotContain("User-Agent:", headers); } })); Assert.True(connectionAccepted); } public static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } public static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false, false }; foreach (bool wrapCredsInCache in BoolValues) { foreach (bool connectionCloseAfter407 in BoolValues) { yield return new object[] { new NetworkCredential("username", "password"), wrapCredsInCache, connectionCloseAfter407 }; yield return new object[] { new NetworkCredential("username", "password", "domain"), wrapCredsInCache, connectionCloseAfter407 }; } } } private sealed class TrackDisposalProxy : IWebProxy, IDisposable { public bool Disposed; public bool ProxyUsed; public void Dispose() => Disposed = true; public Uri GetProxy(Uri destination) { ProxyUsed = true; return null; } public bool IsBypassed(Uri host) { ProxyUsed = true; return true; } public ICredentials Credentials { get => null; set { } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Net.Http.Headers; using System.Net.Sockets; using System.Net.Test.Common; using System.Text; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Microsoft.DotNet.RemoteExecutor; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; #if WINHTTPHANDLER_TEST using HttpClientHandler = System.Net.Http.WinHttpClientHandler; #endif public abstract class HttpClientHandler_Proxy_Test : HttpClientHandlerTestBase { public HttpClientHandler_Proxy_Test(ITestOutputHelper output) : base(output) { } [Fact] public async Task Dispose_HandlerWithProxy_ProxyNotDisposed() { if (IsWinHttpHandler && UseVersion >= HttpVersion20.Value) { return; } var proxy = new TrackDisposalProxy(); await LoopbackServerFactory.CreateClientAndServerAsync(async uri => { using (HttpClientHandler handler = CreateHttpClientHandler()) { handler.UseProxy = true; handler.Proxy = proxy; using (HttpClient client = CreateHttpClient(handler)) { Assert.Equal("hello", await client.GetStringAsync(uri)); } } }, async server => { await server.HandleRequestAsync(content: "hello"); }); Assert.True(proxy.ProxyUsed); Assert.False(proxy.Disposed); } [ActiveIssue("https://github.com/dotnet/runtime/issues/1507")] [OuterLoop("Uses external servers")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] [InlineData(AuthenticationSchemes.Ntlm, true, false)] [InlineData(AuthenticationSchemes.Negotiate, true, false)] [InlineData(AuthenticationSchemes.Basic, false, false)] [InlineData(AuthenticationSchemes.Basic, true, false)] [InlineData(AuthenticationSchemes.Digest, false, false)] [InlineData(AuthenticationSchemes.Digest, true, false)] [InlineData(AuthenticationSchemes.Ntlm, false, false)] [InlineData(AuthenticationSchemes.Negotiate, false, false)] [InlineData(AuthenticationSchemes.Basic, false, true)] [InlineData(AuthenticationSchemes.Basic, true, true)] [InlineData(AuthenticationSchemes.Digest, false, true)] [InlineData(AuthenticationSchemes.Digest, true, true)] public async Task AuthProxy__ValidCreds_ProxySendsRequestToServer( AuthenticationSchemes proxyAuthScheme, bool secureServer, bool proxyClosesConnectionAfterFirst407Response) { if (!PlatformDetection.IsWindows && (proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm)) { // CI machines don't have GSSAPI module installed and will fail with error from // System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle(): // "GSSAPI operation failed with error - An invalid status code was supplied // Configuration file does not specify default realm)." return; } Uri serverUri = secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer; var options = new LoopbackProxyServer.Options { AuthenticationSchemes = proxyAuthScheme, ConnectionCloseAfter407 = proxyClosesConnectionAfterFirst407Response }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyServer.Uri); handler.Proxy.Credentials = new NetworkCredential("username", "password"); using (HttpResponseMessage response = await client.GetAsync(serverUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } } } public static bool IsSocketsHttpHandlerAndRemoteExecutorSupported => !HttpClientHandlerTestBase.IsWinHttpHandler && RemoteExecutor.IsSupported; [OuterLoop("Uses external servers")] [ConditionalFact(nameof(IsSocketsHttpHandlerAndRemoteExecutorSupported))] public void Proxy_UseEnvironmentVariableToSetSystemProxy_RequestGoesThruProxy() { RemoteExecutor.Invoke(async (useVersionString) => { var options = new LoopbackProxyServer.Options { AddViaRequestHeader = true }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { Environment.SetEnvironmentVariable("http_proxy", proxyServer.Uri.AbsoluteUri.ToString()); using (HttpClient client = CreateHttpClient(useVersionString)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string body = await response.Content.ReadAsStringAsync(); Assert.Contains(proxyServer.ViaHeader, body); } } }, UseVersion.ToString()).Dispose(); } const string BasicAuth = "Basic"; const string content = "This is a test"; private static ICredentials ConstructCredentials(NetworkCredential cred, Uri uriPrefix, string authType, bool wrapCredsInCache) { if (wrapCredsInCache) { var cache = new CredentialCache(); cache.Add(uriPrefix, authType, cred); return cache; } return cred; } private void ValidateProxyBasicAuthentication(LoopbackProxyServer proxyServer, NetworkCredential cred) { if (cred != null) { string expectedAuth = string.IsNullOrEmpty(cred.Domain) ? $"{cred.UserName}:{cred.Password}" : $"{cred.Domain}\\{cred.UserName}:{cred.Password}"; _output.WriteLine($"expectedAuth={expectedAuth}"); string expectedAuthHash = Convert.ToBase64String(Encoding.UTF8.GetBytes(expectedAuth)); // Check last request to proxy server. Handlers that don't use // pre-auth for proxy will make 2 requests. int requestCount = proxyServer.Requests.Count; _output.WriteLine($"proxyServer.Requests.Count={requestCount}"); Assert.Equal(BasicAuth, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueScheme); Assert.Equal(expectedAuthHash, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueToken); } } [OuterLoop("Uses external servers")] [Theory] [MemberData(nameof(CredentialsForProxy))] public async Task AuthenticatedProxiedRequest_GetAsyncWithCreds_Success(NetworkCredential cred, bool wrapCredsInCache, bool connectionCloseAfter407) { var options = new LoopbackProxyServer.Options { AuthenticationSchemes = cred != null ? AuthenticationSchemes.Basic : AuthenticationSchemes.None, ConnectionCloseAfter407 = connectionCloseAfter407 }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = ConstructCredentials(cred, proxyServer.Uri, BasicAuth, wrapCredsInCache) }; using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); ValidateProxyBasicAuthentication(proxyServer, cred); } } } [OuterLoop("Uses external servers")] [Theory] [MemberData(nameof(CredentialsForProxy))] public async Task AuthenticatedProxyTunnelRequest_PostAsyncWithCreds_Success(NetworkCredential cred, bool wrapCredsInCache, bool connectionCloseAfter407) { if (IsWinHttpHandler) { return; } var options = new LoopbackProxyServer.Options { AuthenticationSchemes = cred != null ? AuthenticationSchemes.Basic : AuthenticationSchemes.None, ConnectionCloseAfter407 = connectionCloseAfter407 }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = ConstructCredentials(cred, proxyServer.Uri, BasicAuth, wrapCredsInCache) }; using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, new StringContent(content))) { string responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, content); ValidateProxyBasicAuthentication(proxyServer, cred); } } } [OuterLoop("Uses external servers")] [Theory] [MemberData(nameof(BypassedProxies))] public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = proxy; using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [OuterLoop("Uses external servers")] [Fact] public async Task AuthenticatedProxiedRequest_GetAsyncWithNoCreds_ProxyAuthenticationRequiredStatusCode() { var options = new LoopbackProxyServer.Options { AuthenticationSchemes = AuthenticationSchemes.Basic }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } } } [Fact] public async Task AuthenticatedProxyTunnelRequest_PostAsyncWithNoCreds_Throws() { if (IsWinHttpHandler) { return; } var options = new LoopbackProxyServer.Options { AuthenticationSchemes = AuthenticationSchemes.Basic, }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; using (HttpClient client = CreateHttpClient(handler)) { HttpRequestException e = await Assert.ThrowsAnyAsync<HttpRequestException>(async () => await client.PostAsync("https://nosuchhost.invalid", new StringContent(content))); Assert.Contains("407", e.Message); } } } [Fact] public async Task Proxy_SslProxyUnsupported_Throws() { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy("https://" + Guid.NewGuid().ToString("N")); Type expectedType = IsWinHttpHandler ? typeof(HttpRequestException) : typeof(NotSupportedException); await Assert.ThrowsAsync(expectedType, () => client.GetAsync("http://" + Guid.NewGuid().ToString("N"))); } } [Fact] public async Task ProxyTunnelRequest_GetAsync_Success() { if (IsWinHttpHandler) { return; } const string Content = "Hello world"; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create()) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; using (HttpClient client = CreateHttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server, uri) => { Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri)); Task<HttpResponseMessage> clientTask = client.GetAsync(uri); await server.AcceptConnectionSendResponseAndCloseAsync(content: Content); using (var response = await clientTask) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Content, await response.Content.ReadAsStringAsync()); } }, options); } Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine); } } [Fact] public async Task ProxyTunnelRequest_MaxConnectionsSetButDoesNotApplyToProxyConnect_Success() { if (IsWinHttpHandler) { return; } const string Content = "Hello world"; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create()) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; handler.MaxConnectionsPerServer = 1; using (HttpClient client = CreateHttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server1, uri1) => { await LoopbackServer.CreateServerAsync(async (server2, uri2) => { Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri1)); Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri2)); Task<HttpResponseMessage> clientTask1 = client.GetAsync(uri1); Task<HttpResponseMessage> clientTask2 = client.GetAsync(uri2); await server1.AcceptConnectionAsync(async connection1 => { await server2.AcceptConnectionAsync(async connection2 => { await connection1.HandleRequestAsync(content: Content); await connection2.HandleRequestAsync(content: Content); }); }); using (var response1 = await clientTask1) { Assert.Equal(HttpStatusCode.OK, response1.StatusCode); Assert.Equal(Content, await response1.Content.ReadAsStringAsync()); } using (var response2 = await clientTask2) { Assert.Equal(HttpStatusCode.OK, response2.StatusCode); Assert.Equal(Content, await response2.Content.ReadAsStringAsync()); } }, options); }, options); } Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine); Assert.Contains("CONNECT", proxyServer.Requests[1].RequestLine); } } [Fact] public async Task ProxyTunnelRequest_OriginServerSendsProxyAuthChallenge_NoProxyAuthPerformed() { if (IsWinHttpHandler) { return; } using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create()) { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = ConstructCredentials(new NetworkCredential("username", "password"), proxyServer.Uri, BasicAuth, true) }; handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; using (HttpClient client = CreateHttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server, uri) => { Assert.Equal(proxyServer.Uri, handler.Proxy.GetProxy(uri)); Task<HttpResponseMessage> clientTask = client.GetAsync(uri); await server.AcceptConnectionSendResponseAndCloseAsync(statusCode: HttpStatusCode.ProxyAuthenticationRequired, additionalHeaders: "Proxy-Authenticate: Basic"); using (var response = await clientTask) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } }, options); } Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public async Task ProxyAuth_Digest_Succeeds() { const string expectedUsername = "user"; const string expectedPassword = "password"; const string authHeader = "Proxy-Authenticate: Digest realm=\"NetCore\", nonce=\"PwOnWgAAAAAAjnbW438AAJSQi1kAAAAA\", qop=\"auth\", stale=false\r\n"; LoopbackServer.Options options = new LoopbackServer.Options { IsProxy = true, Username = expectedUsername, Password = expectedPassword }; var proxyCreds = new NetworkCredential(expectedUsername, expectedPassword); await LoopbackServer.CreateServerAsync(async (proxyServer, proxyUrl) => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUrl) { Credentials = proxyCreds }; // URL does not matter. We will get response from "proxy" code below. Task<HttpResponseMessage> clientTask = client.GetAsync($"http://notarealserver.com/"); // Send Digest challenge. Task<List<string>> serverTask = proxyServer.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.ProxyAuthenticationRequired, authHeader); if (clientTask == await Task.WhenAny(clientTask, serverTask).WaitAsync(TestHelper.PassingTestTimeout)) { // Client task shouldn't have completed successfully; propagate failure. Assert.NotEqual(TaskStatus.RanToCompletion, clientTask.Status); await clientTask; } // Verify user & password. serverTask = proxyServer.AcceptConnectionPerformAuthenticationAndCloseAsync(""); await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { clientTask, serverTask }, TestHelper.PassingTestTimeoutMilliseconds); Assert.Equal(HttpStatusCode.OK, clientTask.Result.StatusCode); } }, options); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public async Task MultiProxy_PAC_Failover_Succeeds() { if (IsWinHttpHandler) { // PAC-based failover is only supported on Windows/SocketsHttpHandler return; } // Create our failing proxy server. // Bind a port to reserve it, but don't start listening yet. The first Connect() should fail and cause a fail-over. using Socket failingProxyServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); failingProxyServer.Bind(new IPEndPoint(IPAddress.Loopback, 0)); var failingEndPoint = (IPEndPoint)failingProxyServer.LocalEndPoint; using LoopbackProxyServer succeedingProxyServer = LoopbackProxyServer.Create(); string proxyConfigString = $"{failingEndPoint.Address}:{failingEndPoint.Port} {succeedingProxyServer.Uri.Host}:{succeedingProxyServer.Uri.Port}"; // Create a WinInetProxyHelper and override its values with our own. object winInetProxyHelper = Activator.CreateInstance(typeof(HttpClient).Assembly.GetType("System.Net.Http.WinInetProxyHelper", true), true); winInetProxyHelper.GetType().GetField("_autoConfigUrl", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, null); winInetProxyHelper.GetType().GetField("_autoDetect", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, false); winInetProxyHelper.GetType().GetField("_proxy", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, proxyConfigString); winInetProxyHelper.GetType().GetField("_proxyBypass", Reflection.BindingFlags.Instance | Reflection.BindingFlags.NonPublic).SetValue(winInetProxyHelper, null); // Create a HttpWindowsProxy with our custom WinInetProxyHelper. IWebProxy httpWindowsProxy = (IWebProxy)Activator.CreateInstance(typeof(HttpClient).Assembly.GetType("System.Net.Http.HttpWindowsProxy", true), Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance, null, new[] { winInetProxyHelper, null }, null); Task<bool> nextFailedConnection = null; // Run a request with that proxy. Task requestTask = LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using HttpClientHandler handler = CreateHttpClientHandler(); using HttpClient client = CreateHttpClient(handler); handler.Proxy = httpWindowsProxy; // First request is expected to hit the failing proxy server, then failover to the succeeding proxy server. Assert.Equal("foo", await client.GetStringAsync(uri)); // Second request should start directly at the succeeding proxy server. // So, start listening on our failing proxy server to catch if it tries to connect. failingProxyServer.Listen(1); nextFailedConnection = WaitForNextFailedConnection(); Assert.Equal("bar", await client.GetStringAsync(uri)); }, async server => { await server.HandleRequestAsync(statusCode: HttpStatusCode.OK, content: "foo"); await server.HandleRequestAsync(statusCode: HttpStatusCode.OK, content: "bar"); }); // Wait for request to finish. await requestTask; // Triggers WaitForNextFailedConnection to stop, and then check // to ensure we haven't got any further requests against it. failingProxyServer.Dispose(); Assert.False(await nextFailedConnection); Assert.Equal(2, succeedingProxyServer.Requests.Count); async Task<bool> WaitForNextFailedConnection() { try { (await failingProxyServer.AcceptAsync()).Dispose(); return true; } catch (SocketException ex) when (ex.SocketErrorCode == SocketError.OperationAborted) { // Dispose() of the loopback server will cause AcceptAsync() in EstablishConnectionAsync() to abort. return false; } } } [Theory] [InlineData("1.2.3.4")] [InlineData("1.2.3.4:8080")] [InlineData("[::1234]")] [InlineData("[::1234]:8080")] public async Task ProxiedIPAddressRequest_NotDefaultPort_CorrectlyFormatted(string host) { string uri = "http://" + host; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(uri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"GET {uri}/ HTTP/1.1", headers); })); Assert.True(connectionAccepted); } public static IEnumerable<object[]> DestinationHost_MemberData() { yield return new object[] { "nosuchhost.invalid" }; yield return new object[] { "1.2.3.4" }; yield return new object[] { "[::1234]" }; } [Theory] [MemberData(nameof(DestinationHost_MemberData))] public async Task ProxiedRequest_DefaultPort_PortStrippedOffInUri(string host) { string addressUri = $"http://{host}:80/"; string expectedAddressUri = $"http://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"GET {expectedAddressUri} HTTP/1.1", headers); })); Assert.True(connectionAccepted); } [Theory] [MemberData(nameof(DestinationHost_MemberData))] public async Task ProxyTunnelRequest_PortSpecified_NotStrippedOffInUri(string host) { // Https proxy request will use CONNECT tunnel, even the default 443 port is specified, it will not be stripped off. string requestTarget = $"{host}:443"; string addressUri = $"https://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"CONNECT {requestTarget} HTTP/1.1", headers); })); Assert.True(connectionAccepted); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ProxyTunnelRequest_UserAgentHeaderAdded(bool addUserAgentHeader) { if (IsWinHttpHandler) { return; // Skip test since the fix is only in SocketsHttpHandler. } string host = "nosuchhost.invalid"; string addressUri = $"https://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; if (addUserAgentHeader) { client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Mozilla", "5.0")); } try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"CONNECT {host}:443 HTTP/1.1", headers); if (addUserAgentHeader) { Assert.Contains("User-Agent: Mozilla/5.0", headers); } else { Assert.DoesNotContain("User-Agent:", headers); } })); Assert.True(connectionAccepted); } public static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } public static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false, false }; foreach (bool wrapCredsInCache in BoolValues) { foreach (bool connectionCloseAfter407 in BoolValues) { yield return new object[] { new NetworkCredential("username", "password"), wrapCredsInCache, connectionCloseAfter407 }; yield return new object[] { new NetworkCredential("username", "password", "domain"), wrapCredsInCache, connectionCloseAfter407 }; } } } private sealed class TrackDisposalProxy : IWebProxy, IDisposable { public bool Disposed; public bool ProxyUsed; public void Dispose() => Disposed = true; public Uri GetProxy(Uri destination) { ProxyUsed = true; return null; } public bool IsBypassed(Uri host) { ProxyUsed = true; return true; } public ICredentials Credentials { get => null; set { } } } } }
-1
dotnet/runtime
66,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftLeftLogicalWideningUpper.Vector128.UInt16.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 ShiftLeftLogicalWideningUpper_Vector128_UInt16_1() { var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_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 ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray, UInt32[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt16, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1 testClass) { var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1 testClass) { fixed (Vector128<UInt16>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 1; private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector128<UInt16> _clsVar; private Vector128<UInt16> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data, 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.ShiftLeftLogicalWideningUpper( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1(); fixed (Vector128<UInt16>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogicalWideningUpper(firstOp, Imm, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalWideningUpper)}<UInt32>(Vector128<UInt16>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLeftLogicalWideningUpper_Vector128_UInt16_1() { var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_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 ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray, UInt32[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt16, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1 testClass) { var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1 testClass) { fixed (Vector128<UInt16>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 1; private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector128<UInt16> _clsVar; private Vector128<UInt16> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data, 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.ShiftLeftLogicalWideningUpper( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_UInt16_1(); fixed (Vector128<UInt16>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((UInt16*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogicalWideningUpper(firstOp, Imm, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalWideningUpper)}<UInt32>(Vector128<UInt16>, 1): {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,145
Fix clash between tentative method optimizations
This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
MichalStrehovsky
2022-03-03T16:32:47Z
2022-03-07T16:49:51Z
154386d63b3ba55ce3251fa4caf3dfa89279d982
b0d1e89497bfa7a7b602a1d1af2faa97af96c88d
Fix clash between tentative method optimizations. This pull request pretty much became a rollback of https://github.com/dotnet/runtimelab/pull/658 with a regression test to make sure if https://github.com/dotnet/runtimelab/pull/658 is reintroduced, we do it properly. ~~When we were in the situation of the newly added test, we would try to generate method body on the abstract class. Such method body is not actually reachable.~~ ~~Saves 500 bytes on a hello world. Fixes a compiler assert (that might be more serious sometimes).~~
./src/libraries/Common/src/Interop/Windows/WinMm/Interop.waveOutWrite.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class WinMM { /// <summary> /// This function sends a data block to the specified waveform output device. /// </summary> /// <param name="hwo">Handle to the waveform-audio output device.</param> /// <param name="pwh">Pointer to a WaveHeader structure containing information /// about the data block.</param> /// <param name="cbwh">Size, in bytes, of the WaveHeader structure.</param> /// <returns>MMSYSERR</returns> [GeneratedDllImport(Libraries.WinMM)] internal static partial MMSYSERR waveOutWrite(IntPtr hwo, IntPtr pwh, int cbwh); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class WinMM { /// <summary> /// This function sends a data block to the specified waveform output device. /// </summary> /// <param name="hwo">Handle to the waveform-audio output device.</param> /// <param name="pwh">Pointer to a WaveHeader structure containing information /// about the data block.</param> /// <param name="cbwh">Size, in bytes, of the WaveHeader structure.</param> /// <returns>MMSYSERR</returns> [GeneratedDllImport(Libraries.WinMM)] internal static partial MMSYSERR waveOutWrite(IntPtr hwo, IntPtr pwh, int cbwh); } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Private.Xml/src/System.Private.Xml.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <RootNamespace>System.Xml</RootNamespace> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)</TargetFrameworks> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)System\Text\StringBuilderCache.cs" Link="Common\System\StringBuilderCache.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> <Compile Include="System\Xml\BinaryXml\XmlBinaryReader.cs" /> <Compile Include="System\Xml\BinaryXml\BinXmlToken.cs" /> <Compile Include="System\Xml\BinaryXml\SqlUtils.cs" /> <Compile Include="Misc\HResults.cs" /> <Compile Include="System\Xml\AsyncHelper.cs" /> <Compile Include="System\Xml\Base64Decoder.cs" /> <Compile Include="System\Xml\Base64Encoder.cs" /> <Compile Include="System\Xml\Base64EncoderAsync.cs" /> <Compile Include="System\Xml\BinHexDecoder.cs" /> <Compile Include="System\Xml\BinHexEncoder.cs" /> <Compile Include="System\Xml\BinHexEncoderAsync.cs" /> <Compile Include="System\Xml\Bits.cs" /> <Compile Include="System\Xml\BitStack.cs" /> <Compile Include="System\Xml\ByteStack.cs" /> <Compile Include="System\Xml\Core\HtmlEncodedRawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>HtmlEncodedRawTextWriter.tt</DependentUpon> </Compile> <Compile Include="System\Xml\Core\HtmlUtf8RawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>HtmlUtf8RawTextWriter.tt</DependentUpon> </Compile> <Compile Include="System\Xml\Core\TextEncodedRawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>TextEncodedRawTextWriter.tt</DependentUpon> </Compile> <Compile Include="System\Xml\Core\TextUtf8RawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>TextUtf8RawTextWriter.tt</DependentUpon> </Compile> <None Include="System\Xml\Core\HtmlEncodedRawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>HtmlEncodedRawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\HtmlRawTextWriterGenerator.ttinclude" /> <None Include="System\Xml\Core\HtmlUtf8RawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>HtmlUtf8RawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\RawTextWriter.ttinclude" /> <None Include="System\Xml\Core\TextEncodedRawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>TextEncodedRawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\TextRawTextWriterGenerator.ttinclude" /> <None Include="System\Xml\Core\TextUtf8RawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>TextUtf8RawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\XmlRawTextWriterGeneratorAsync.ttinclude" /> <None Include="System\Xml\Core\XmlRawTextWriterGenerator.ttinclude" /> <None Include="System\Xml\Core\RawTextWriterEncoded.ttinclude" /> <Content Include="System\Xml\Core\XmlEncodedRawTextWriter.tt"> <LastGenOutput>XmlEncodedRawTextWriter.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlEncodedRawTextWriter.cs"> <DependentUpon>XmlEncodedRawTextWriter.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <Content Include="System\Xml\Core\XmlEncodedRawTextWriterAsync.tt"> <LastGenOutput>XmlEncodedRawTextWriterAsync.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlEncodedRawTextWriterAsync.cs"> <DependentUpon>XmlEncodedRawTextWriterAsync.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <None Include="System\Xml\Core\RawTextWriterUtf8.ttinclude" /> <Content Include="System\Xml\Core\XmlUtf8RawTextWriter.tt"> <LastGenOutput>XmlUtf8RawTextWriter.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlUtf8RawTextWriter.cs"> <DependentUpon>XmlUtf8RawTextWriter.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <Content Include="System\Xml\Core\XmlUtf8RawTextWriterAsync.tt"> <LastGenOutput>XmlUtf8RawTextWriterAsync.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlUtf8RawTextWriterAsync.cs"> <DependentUpon>XmlUtf8RawTextWriterAsync.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <Compile Include="System\Xml\DiagnosticsSwitches.cs" /> <Compile Include="System\Xml\Dom\XmlNamedNodeMap.SmallXmlNodeList.cs" /> <Compile Include="System\Xml\EmptyEnumerator.cs" /> <Compile Include="System\Xml\HWStack.cs" /> <Compile Include="System\Xml\IApplicationResourceStreamResolver.cs" /> <Compile Include="System\Xml\IHasXmlNode.cs" /> <Compile Include="System\Xml\IXmlLineInfo.cs" /> <Compile Include="System\Xml\IXmlNamespaceResolver.cs" /> <Compile Include="System\Xml\LineInfo.cs" /> <Compile Include="System\Xml\MTNameTable.cs" /> <Compile Include="System\Xml\NameTable.cs" /> <Compile Include="System\Xml\Ref.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationEventSource.cs" /> <Compile Include="System\Xml\ValidateNames.cs" /> <Compile Include="System\Xml\XmlCharType.cs" /> <Compile Include="System\Xml\XmlComplianceUtil.cs" /> <Compile Include="System\Xml\XmlConvert.cs" /> <Compile Include="System\Xml\XmlDownloadManager.cs" /> <Compile Include="System\Xml\XmlDownloadManagerAsync.cs" /> <Compile Include="System\Xml\XmlEncoding.cs" /> <Compile Include="System\Xml\XmlException.cs" /> <Compile Include="System\Xml\XmlNamespacemanager.cs" /> <Compile Include="System\Xml\XmlNamespaceScope.cs" /> <Compile Include="System\Xml\XmlNameTable.cs" /> <Compile Include="System\Xml\XmlNodeOrder.cs" /> <Compile Include="System\Xml\XmlNodeType.cs" /> <Compile Include="System\Xml\XmlNullResolver.cs" /> <Compile Include="System\Xml\XmlQualifiedName.cs" /> <Compile Include="System\Xml\XmlReservedNs.cs" /> <Compile Include="System\Xml\XmlResolver.cs" /> <Compile Include="System\Xml\XmlResolverAsync.cs" /> <Compile Include="System\Xml\XmlSecureResolver.cs" /> <Compile Include="System\Xml\XmlSecureResolverAsync.cs" /> <Compile Include="System\Xml\XmlUrlResolver.cs" /> <Compile Include="System\Xml\XmlUrlResolverAsync.cs" /> <Compile Include="System\Xml\Core\CharEntityEncoderFallback.cs" /> <Compile Include="System\Xml\Core\ConformanceLevel.cs" /> <Compile Include="System\Xml\Core\DtdProcessing.cs" /> <Compile Include="System\Xml\Core\EntityHandling.cs" /> <Compile Include="System\Xml\Core\IDtdInfo.cs" /> <Compile Include="System\Xml\Core\IDtdParser.cs" /> <Compile Include="System\Xml\Core\IDtdParserAsync.cs" /> <Compile Include="System\Xml\Core\IDtdParserAdapter.cs" /> <Compile Include="System\Xml\Core\IDtdParserAdapterAsync.cs" /> <Compile Include="System\Xml\Core\IncrementalReadDecoders.cs" /> <Compile Include="System\Xml\Core\IValidationEventHandling.cs" /> <Compile Include="System\Xml\Core\NamespaceHandling.cs" /> <Compile Include="System\Xml\Core\NewLineHandling.cs" /> <Compile Include="System\Xml\Core\IRemovableWriter.cs" /> <Compile Include="System\Xml\Core\QueryOutputWriter.cs" /> <Compile Include="System\Xml\Core\QueryOutputWriterV1.cs" /> <Compile Include="System\Xml\Core\ReadContentAsBinaryHelper.cs" /> <Compile Include="System\Xml\Core\ReadContentAsBinaryHelperAsync.cs" /> <Compile Include="System\Xml\Core\ReadOnlyTernaryTree.cs" /> <Compile Include="System\Xml\Core\ReadState.cs" /> <Compile Include="System\Xml\Core\ValidatingReaderNodeData.cs" /> <Compile Include="System\Xml\Core\ValidationType.cs" /> <Compile Include="System\Xml\Core\WhitespaceHandling.cs" /> <Compile Include="System\Xml\Core\XmlAsyncCheckReader.cs" /> <Compile Include="System\Xml\Core\XmlAsyncCheckWriter.cs" /> <Compile Include="System\Xml\Core\XmlAutoDetectWriter.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingReader.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingWriter.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlEventCache.cs" /> <Compile Include="System\Xml\Core\XmlParserContext.cs" /> <Compile Include="System\Xml\Core\XmlRawWriter.cs" /> <Compile Include="System\Xml\Core\XmlRawWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlReader.cs" /> <Compile Include="System\Xml\Core\XmlReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlReaderSettings.cs" /> <Compile Include="System\Xml\Core\XmlSpace.cs" /> <Compile Include="System\Xml\Core\XmlSubtreeReader.cs" /> <Compile Include="System\Xml\Core\XmlSubtreeReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlTextEncoder.cs" /> <Compile Include="System\Xml\Core\XmlTextReader.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImpl.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImplAsync.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImplHelpers.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImplHelpersAsync.cs" /> <Compile Include="System\Xml\Core\XmlTextWriter.cs" /> <Compile Include="System\Xml\Core\XmlValidatingReader.cs" /> <Compile Include="System\Xml\Core\XmlValidatingReaderImpl.cs" /> <Compile Include="System\Xml\Core\XmlValidatingReaderImplAsync.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriter.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriterHelpers.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriterHelpersAsync.cs" /> <Compile Include="System\Xml\Core\XmlWrappingReader.cs" /> <Compile Include="System\Xml\Core\XmlWrappingReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlWrappingWriter.cs" /> <Compile Include="System\Xml\Core\XmlWrappingWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlWriter.cs" /> <Compile Include="System\Xml\Core\XmlWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlWriterSettings.cs" /> <Compile Include="System\Xml\Core\XsdValidatingReader.cs" /> <Compile Include="System\Xml\Core\XsdValidatingReaderAsync.cs" /> <Compile Include="System\Xml\Core\XsdCachingReader.cs" /> <Compile Include="System\Xml\Core\XsdCachingReaderAsync.cs" /> <Compile Include="System\Xml\Dom\DocumentXmlWriter.cs" /> <Compile Include="System\Xml\Dom\DocumentXPathNavigator.cs" /> <Compile Include="System\Xml\Dom\DomNameTable.cs" /> <Compile Include="System\Xml\Dom\XmlAttribute.cs" /> <Compile Include="System\Xml\Dom\XmlAttributeCollection.cs" /> <Compile Include="System\Xml\Dom\XmlCDataSection.cs" /> <Compile Include="System\Xml\Dom\XmlCharacterData.cs" /> <Compile Include="System\Xml\Dom\XmlChildEnumerator.cs" /> <Compile Include="System\Xml\Dom\XmlChildNodes.cs" /> <Compile Include="System\Xml\Dom\XmlComment.cs" /> <Compile Include="System\Xml\Dom\XmlDeclaration.cs" /> <Compile Include="System\Xml\Dom\XmlDocument.cs" /> <Compile Include="System\Xml\Dom\XmlDocumentFragment.cs" /> <Compile Include="System\Xml\Dom\XmlDocumentType.cs" /> <Compile Include="System\Xml\Dom\DocumentSchemaValidator.cs" /> <Compile Include="System\Xml\Dom\XmlDomTextWriter.cs" /> <Compile Include="System\Xml\Dom\XmlElement.cs" /> <Compile Include="System\Xml\Dom\XmlElementList.cs" /> <Compile Include="System\Xml\Dom\XmlEntity.cs" /> <Compile Include="System\Xml\Dom\XmlEntityReference.cs" /> <Compile Include="System\Xml\Dom\XmlEventChangedAction.cs" /> <Compile Include="System\Xml\Dom\XmlImplementation.cs" /> <Compile Include="System\Xml\Dom\XmlLinkedNode.cs" /> <Compile Include="System\Xml\Dom\XmlLoader.cs" /> <Compile Include="System\Xml\Dom\XmlName.cs" /> <Compile Include="System\Xml\Dom\XmlNamedNodemap.cs" /> <Compile Include="System\Xml\Dom\XmlNode.cs" /> <Compile Include="System\Xml\Dom\XmlNodeChangedEventArgs.cs" /> <Compile Include="System\Xml\Dom\XmlNodeChangedEventHandler.cs" /> <Compile Include="System\Xml\Dom\XmlNodeList.cs" /> <Compile Include="System\Xml\Dom\XmlNodeReader.cs" /> <Compile Include="System\Xml\Dom\XmlNotation.cs" /> <Compile Include="System\Xml\Dom\XmlProcessingInstruction.cs" /> <Compile Include="System\Xml\Dom\XmlSignificantWhiteSpace.cs" /> <Compile Include="System\Xml\Dom\XmlText.cs" /> <Compile Include="System\Xml\Dom\XmlUnspecifiedAttribute.cs" /> <Compile Include="System\Xml\Dom\XmlWhitespace.cs" /> <Compile Include="System\Xml\Dom\XPathNodeList.cs" /> <Compile Include="System\Xml\Cache\XPathDocumentBuilder.cs" /> <Compile Include="System\Xml\Cache\XPathDocumentIterator.cs" /> <Compile Include="System\Xml\Cache\XPathDocumentNavigator.cs" /> <Compile Include="System\Xml\Cache\XPathNode.cs" /> <Compile Include="System\Xml\Cache\XPathNodeHelper.cs" /> <Compile Include="System\Xml\Cache\XPathNodeInfoAtom.cs" /> <Compile Include="System\Xml\Resolvers\XmlKnownDtds.cs" /> <Compile Include="System\Xml\Resolvers\XmlPreloadedResolver.cs" /> <Compile Include="System\Xml\Resolvers\XmlPreloadedResolverAsync.cs" /> <Compile Include="System\Xml\XPath\IXPathNavigable.cs" /> <Compile Include="System\Xml\XPath\XPathDocument.cs" /> <Compile Include="System\Xml\XPath\XPathException.cs" /> <Compile Include="System\Xml\XPath\XPathExpr.cs" /> <Compile Include="System\Xml\XPath\XPathItem.cs" /> <Compile Include="System\Xml\XPath\XPathNamespaceScope.cs" /> <Compile Include="System\Xml\XPath\XPathNavigator.cs" /> <Compile Include="System\Xml\XPath\XPathNavigatorKeyComparer.cs" /> <Compile Include="System\Xml\XPath\XPathNavigatorReader.cs" /> <Compile Include="System\Xml\XPath\XPathNodeIterator.cs" /> <Compile Include="System\Xml\XPath\XPathNodeType.cs" /> <Compile Include="System\Xml\XPath\Internal\AbsoluteQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\AstNode.cs" /> <Compile Include="System\Xml\XPath\Internal\AttributeQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Axis.cs" /> <Compile Include="System\Xml\XPath\Internal\BaseAxisQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\BooleanExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\BooleanFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\CacheAxisQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\CacheChildrenQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\CacheOutputQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ChildrenQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ClonableStack.cs" /> <Compile Include="System\Xml\XPath\Internal\CompiledXPathExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\ContextQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DescendantBaseQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DescendantQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DescendantoverDescendantQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DocumentorderQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\EmptyQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ExtensionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\FunctionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Filter.cs" /> <Compile Include="System\Xml\XPath\Internal\FilterQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\FollowingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\FollSiblingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ForwardPositionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Function.cs" /> <Compile Include="System\Xml\XPath\Internal\Group.cs" /> <Compile Include="System\Xml\XPath\Internal\GroupQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\IdQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\IteratorFilter.cs" /> <Compile Include="System\Xml\XPath\Internal\Query.cs" /> <Compile Include="System\Xml\XPath\Internal\LogicalExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\MergeFilterQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\NamespaceQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\NodeFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\NumberFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\NumericExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\Operand.cs" /> <Compile Include="System\Xml\XPath\Internal\OperandQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Operator.cs" /> <Compile Include="System\Xml\XPath\Internal\ParentQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\PrecedingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\PreSiblingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\QueryBuilder.cs" /> <Compile Include="System\Xml\XPath\Internal\UnionExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\ResetableIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\ReversePositionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Root.cs" /> <Compile Include="System\Xml\XPath\Internal\SortQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\StringFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\ValueQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Variable.cs" /> <Compile Include="System\Xml\XPath\Internal\VariableQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathAncestorIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathAncestorQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathArrayIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathAxisIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathChildIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathDescendantIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathEmptyIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathMultyIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathParser.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathScanner.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathSelectionIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathSelfQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathSingletonIterator.cs" /> <Compile Include="System\Xml\Xslt\XslCompiledTransform.cs" /> <Compile Include="System\Xml\Xslt\XsltArgumentList.cs" /> <Compile Include="System\Xml\Xslt\XsltContext.cs" /> <Compile Include="System\Xml\Xslt\XsltException.cs" /> <Compile Include="System\Xml\Xslt\XslTransform.cs" /> <Compile Include="System\Xml\Xslt\XsltSettings.cs" /> <Compile Include="System\Xml\Schema\Asttree.cs" /> <Compile Include="System\Xml\Schema\AutoValidator.cs" /> <Compile Include="System\Xml\Schema\BaseProcessor.cs" /> <Compile Include="System\Xml\Schema\BaseValidator.cs" /> <Compile Include="System\Xml\Schema\BitSet.cs" /> <Compile Include="System\Xml\Schema\Chameleonkey.cs" /> <Compile Include="System\Xml\Schema\CompiledidEntityConstraint.cs" /> <Compile Include="System\Xml\Schema\SchemaSetCompiler.cs" /> <Compile Include="System\Xml\Schema\ConstraintStruct.cs" /> <Compile Include="System\Xml\Schema\ContentValidator.cs" /> <Compile Include="System\Xml\Schema\DataTypeImplementation.cs" /> <Compile Include="System\Xml\Schema\DtdParser.cs" /> <Compile Include="System\Xml\Schema\DtdParserAsync.cs" /> <Compile Include="System\Xml\Schema\DtdValidator.cs" /> <Compile Include="System\Xml\Schema\FacetChecker.cs" /> <Compile Include="System\Xml\Schema\IXmlSchemaInfo.cs" /> <Compile Include="System\Xml\Schema\NamespaceList.cs" /> <Compile Include="System\Xml\Schema\Parser.cs" /> <Compile Include="System\Xml\Schema\ParserAsync.cs" /> <Compile Include="System\Xml\Schema\Preprocessor.cs" /> <Compile Include="System\Xml\Schema\SchemaAttDef.cs" /> <Compile Include="System\Xml\Schema\SchemaBuilder.cs" /> <Compile Include="System\Xml\Schema\SchemaCollectionCompiler.cs" /> <Compile Include="System\Xml\Schema\SchemaCollectionpreProcessor.cs" /> <Compile Include="System\Xml\Schema\SchemaDeclBase.cs" /> <Compile Include="System\Xml\Schema\SchemaElementDecl.cs" /> <Compile Include="System\Xml\Schema\SchemaEntity.cs" /> <Compile Include="System\Xml\Schema\SchemaInfo.cs" /> <Compile Include="System\Xml\Schema\SchemaNames.cs" /> <Compile Include="System\Xml\Schema\SchemaNamespacemanager.cs" /> <Compile Include="System\Xml\Schema\SchemaNotation.cs" /> <Compile Include="System\Xml\Schema\SchemaType.cs" /> <Compile Include="System\Xml\Schema\ValidationEventArgs.cs" /> <Compile Include="System\Xml\Schema\ValidationEventHandler.cs" /> <Compile Include="System\Xml\Schema\ValidationState.cs" /> <Compile Include="System\Xml\Schema\XdrBuilder.cs" /> <Compile Include="System\Xml\Schema\XdrValidator.cs" /> <Compile Include="System\Xml\Schema\XmlAtomicValue.cs" /> <Compile Include="System\Xml\Schema\XmlSchema.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAll.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAnnotated.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAnnotation.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAny.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAnyAttribute.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAppInfo.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAttribute.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAttributeGroup.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAttributeGroupref.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaChoice.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaCollection.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexContentExtension.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexContentRestriction.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContentModel.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContentProcessing.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContentType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaDataType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaDerivationMethod.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaDocumentation.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaElement.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaException.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaExternal.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaFacet.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaForm.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaGroup.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaGroupBase.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaGroupRef.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaIdEntityConstraint.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaImport.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaInclude.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaInfo.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaNotation.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaObject.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaObjectCollection.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaObjectTable.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaParticle.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaRedefine.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSequence.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSet.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaCompilationSettings.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleContentExtension.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleContentRestriction.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeList.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeRestriction.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeUnion.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSubstitutionGroup.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaUse.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaValidationException.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaValidator.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaValidity.cs" /> <Compile Include="System\Xml\Schema\XmlSeverityType.cs" /> <Compile Include="System\Xml\Schema\XmlTokenizedType.cs" /> <Compile Include="System\Xml\Schema\XmlTypeCode.cs" /> <Compile Include="System\Xml\Schema\XmlValueConverter.cs" /> <Compile Include="System\Xml\Schema\XsdBuilder.cs" /> <Compile Include="System\Xml\Schema\XsdDateTime.cs" /> <Compile Include="System\Xml\Schema\XsdDuration.cs" /> <Compile Include="System\Xml\Schema\XsdValidator.cs" /> <Compile Include="System\Xml\Schema\Inference\Infer.cs" /> <Compile Include="System\Xml\Schema\Inference\XmlSchemaInferenceException.cs" /> <Compile Include="System\Xml\Serialization\CodeGenerationoptions.cs" /> <Compile Include="System\Xml\Serialization\CodeGenerator.cs" /> <Compile Include="System\Xml\Serialization\CodeIdentifier.cs" /> <Compile Include="System\Xml\Serialization\CodeIdentifiers.cs" /> <Compile Include="System\Xml\Serialization\Compilation.cs" /> <Compile Include="System\Xml\Serialization\Compiler.cs" /> <Compile Include="System\Xml\Serialization\ContextAwareTables.cs" /> <Compile Include="System\Xml\Serialization\ImportContext.cs" /> <Compile Include="System\Xml\Serialization\indentedWriter.cs" /> <Compile Include="System\Xml\Serialization\IXmlSerializable.cs" /> <Compile Include="System\Xml\Serialization\IXmlTextParser.cs" /> <Compile Include="System\Xml\Serialization\Mappings.cs" /> <Compile Include="System\Xml\Serialization\Models.cs" /> <Compile Include="System\Xml\Serialization\NameTable.cs" /> <Compile Include="System\Xml\Serialization\ReflectionXmlSerializationReader.cs" /> <Compile Include="System\Xml\Serialization\ReflectionXmlSerializationWriter.cs" /> <Compile Include="System\Xml\Serialization\SchemaImporter.cs" /> <Compile Include="System\Xml\Serialization\SchemaObjectWriter.cs" /> <Compile Include="System\Xml\Serialization\SoapAttributeAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapAttributeOverrides.cs" /> <Compile Include="System\Xml\Serialization\SoapAttributes.cs" /> <Compile Include="System\Xml\Serialization\SoapElementAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapEnumAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapIgnoreAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapIncludeAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapReflectionImporter.cs" /> <Compile Include="System\Xml\Serialization\SoapSchemamember.cs" /> <Compile Include="System\Xml\Serialization\SoapTypeAttribute.cs" /> <Compile Include="System\Xml\Serialization\SourceInfo.cs" /> <Compile Include="System\Xml\Serialization\Types.cs" /> <Compile Include="System\Xml\Serialization\XmlAnyAttributeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlAnyElementAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlAnyElementAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlArrayAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlArrayItemAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlArrayItemAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlAttributeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlAttributeOverrides.cs" /> <Compile Include="System\Xml\Serialization\XmlAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlChoiceIdentifierAttribute.cs" /> <Compile Include="System\Xml\Serialization\Xmlcustomformatter.cs" /> <Compile Include="System\Xml\Serialization\XmlElementAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlElementAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlEnumAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlIgnoreAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlIncludeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlMapping.cs" /> <Compile Include="System\Xml\Serialization\XmlMemberMapping.cs" /> <Compile Include="System\Xml\Serialization\XmlMembersMapping.cs" /> <Compile Include="System\Xml\Serialization\XmlNamespaceDeclarationsAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlReflectionImporter.cs" /> <Compile Include="System\Xml\Serialization\XmlReflectionMember.cs" /> <Compile Include="System\Xml\Serialization\XmlRootAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemaExporter.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemaImporter.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemaProviderAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemas.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationGeneratedCode.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationILGen.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationReader.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationReaderILGen.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationWriter.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationWriterILGen.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerAssemblyAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializer.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerFactory.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerNamespaces.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerVersionAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlTextAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlTypeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlTypeMapping.cs" /> <Compile Include="System\Xml\Serialization\_Events.cs" /> <Compile Include="System\Xml\Serialization\TypeExtensions.cs" /> <Compile Include="System\Xml\Serialization\PrimitiveXmlSerializers.cs" /> <Compile Include="System\Xml\Serialization\Configuration\DateTimeSerializationSection.cs" /> <Compile Include="System\Xml\Extensions\ExtensionMethods.cs" /> <Compile Include="System\Xml\Serialization\Globals.cs" /> </ItemGroup> <!-- Embedded DTD files --> <ItemGroup> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml1-strict.dtd"> <LogicalName>xhtml1-strict.dtd</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml1-transitional.dtd"> <LogicalName>xhtml1-transitional.dtd</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml1-frameset.dtd"> <LogicalName>xhtml1-frameset.dtd</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml-lat1.ent"> <LogicalName>xhtml-lat1.ent</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml-special.ent"> <LogicalName>xhtml-special.ent</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml-symbol.ent"> <LogicalName>xhtml-symbol.ent</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\RSS091\no_comments\rss-0.91.dtd"> <LogicalName>rss-0.91.dtd</LogicalName> </EmbeddedResource> </ItemGroup> <ItemGroup> <Reference Include="System.Reflection.Emit" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Collections.Specialized" /> <Reference Include="System.Console" /> <Reference Include="System.Diagnostics.TraceSource" /> <Reference Include="System.Diagnostics.Tracing" /> <Reference Include="System.IO.FileSystem" /> <Reference Include="System.Linq.Expressions" /> <Reference Include="System.Memory" /> <Reference Include="System.Net.Http" /> <Reference Include="System.Net.Primitives" /> <Reference Include="System.ObjectModel" /> <Reference Include="System.Reflection.Primitives" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.CompilerServices.Unsafe" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Runtime.Loader" /> <Reference Include="System.Security.Cryptography" /> <Reference Include="System.Security.Cryptography.Algorithms" /> <Reference Include="System.Text.Encoding.Extensions" /> <Reference Include="System.Text.RegularExpressions" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Thread" /> </ItemGroup> <ItemGroup> <Compile Include="System\Xml\Xsl\IlGen\GenerateHelper.cs" /> <Compile Include="System\Xml\Xsl\IlGen\IteratorDescriptor.cs" /> <Compile Include="System\Xml\Xsl\IlGen\OptimizerPatterns.cs" /> <Compile Include="System\Xml\Xsl\IlGen\StaticDataManager.cs" /> <Compile Include="System\Xml\Xsl\IlGen\TailCallAnalyzer.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILAnnotation.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILConstructAnalyzer.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILModule.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILOptimization.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILOptimizerVisitor.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILTrace.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlIlTypeHelper.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlIlVisitor.cs" /> <Compile Include="System\Xml\Xsl\XmlIlGenerator.cs" /> <Compile Include="System\Xml\Xsl\XmlILCommand.cs" /> <Compile Include="System\Xml\Xsl\ISourceLineInfo.cs" /> <Compile Include="System\Xml\Xsl\ListBase.cs" /> <Compile Include="System\Xml\Xsl\Pair.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilBinary.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilChoice.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilCloneVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilDataSource.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilExpression.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilFactory.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilFunction.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilInvoke.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilInvokeEarlyBound.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilInvokeLateBound.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilIterator.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilList.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilLiteral.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilLoop.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilName.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilNode.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilNodeType.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilParameter.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilPatternFactory.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilPatternVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilReference.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilReplaceVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilScopedVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilSortKey.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilStrConcat.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilTargetType.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilTernary.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilTypeChecker.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilUnary.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilValidationVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilXmlWriter.cs" /> <Compile Include="System\Xml\Xsl\QIL\SerializationHints.cs" /> <Compile Include="System\Xml\Xsl\QIL\SubstitutionList.cs" /> <Compile Include="System\Xml\Xsl\QIL\WhitespaceRule.cs" /> <Compile Include="System\Xml\Xsl\QueryReaderSettings.cs" /> <Compile Include="System\Xml\Xsl\Runtime\ContentIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\DecimalFormatter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\DocumentOrderComparer.cs" /> <Compile Include="System\Xml\Xsl\Runtime\DodSequenceMerge.cs" /> <Compile Include="System\Xml\Xsl\Runtime\EarlyBoundInfo.cs" /> <Compile Include="System\Xml\Xsl\Runtime\NumberFormatter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\RtfNavigator.cs" /> <Compile Include="System\Xml\Xsl\Runtime\SetIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\SiblingIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\StringConcat.cs" /> <Compile Include="System\Xml\Xsl\Runtime\TreeIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\WhitespaceRuleLookup.cs" /> <Compile Include="System\Xml\Xsl\Runtime\WhitespaceRuleReader.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlAggregates.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlAttributeCache.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlCollation.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlExtensionFunction.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlILIndex.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlILStorageConverter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlNavigatorFilter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlNavigatorStack.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryContext.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryOutput.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryRuntime.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQuerySequence.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryStaticData.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlRawWriterWrapper.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlSequenceWriter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlSortKey.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlSortKeyAccumulator.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XslNumber.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XsltConvert.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XsltFunctions.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XsltLibrary.cs" /> <Compile Include="System\Xml\Xsl\SourceLineInfo.cs" /> <Compile Include="System\Xml\Xsl\XmlNodeKindFlags.cs" /> <Compile Include="System\Xml\Xsl\XmlQualifiedNameTest.cs" /> <Compile Include="System\Xml\Xsl\XmlQueryCardinality.cs" /> <Compile Include="System\Xml\Xsl\XmlQueryType.cs" /> <Compile Include="System\Xml\Xsl\XmlQueryTypeFactory.cs" /> <Compile Include="System\Xml\Xsl\XPathConvert.cs" /> <Compile Include="System\Xml\Xsl\XPath\IXpathBuilder.cs" /> <Compile Include="System\Xml\Xsl\XPath\IXPathEnvironment.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathAxis.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathBuilder.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathCompileException.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathContext.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathOperator.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathParser.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathQilFactory.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathScanner.cs" /> <Compile Include="System\Xml\Xsl\XslException.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Action.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ActionFrame.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ApplyImportsAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ApplyTemplatesAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\AttributeAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\AttributeSetAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Avt.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\AvtEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\BeginEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\BuilderInfo.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CallTemplateAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ChooseAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CommentAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CompiledAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Compiler.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ContainerAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyAttributesAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyCodeAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyNamespacesAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyNodeSetAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyOfAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\DbgCompiler.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\DocumentScope.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ElementAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\EndEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Event.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ForEachAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\HtmlProps.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\IfAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\InputScope.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\InputScopeManager.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\IRecordOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\MessageAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NamespaceDecl.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NameSpaceEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NavigatorInput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NavigatorOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\newinstructionaction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NumberAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\OutKeywords.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\OutputScope.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\OutputScopeManager.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\PrefixQName.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ProcessingInstructionAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Processor.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ReaderOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\RecordBuilder.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\RootAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\SequentialOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\SortAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\StateMachine.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\StringOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Stylesheet.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateBaseAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateLookupAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateManager.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextOnlyOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TheQuery.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\UseAttributeSetsAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ValueOfAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\VariableAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\WithParamAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\WriterOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\XsltCompileContext.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\XsltDebugger.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\XsltOutput.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Compiler.cs" /> <Compile Include="System\Xml\Xsl\Xslt\CompilerError.cs" /> <Compile Include="System\Xml\Xsl\Xslt\CompilerScopeManager.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Focus.cs" /> <Compile Include="System\Xml\Xsl\Xslt\IErrorHelper.cs" /> <Compile Include="System\Xml\Xsl\Xslt\InvokeGenerator.cs" /> <Compile Include="System\Xml\Xsl\Xslt\KeyMatchBuilder.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Keywords.cs" /> <Compile Include="System\Xml\Xsl\Xslt\MatcherBuilder.cs" /> <Compile Include="System\Xml\Xsl\Xslt\OutputScopeManager.cs" /> <Compile Include="System\Xml\Xsl\Xslt\QilGenerator.cs" /> <Compile Include="System\Xml\Xsl\Xslt\QilGeneratorEnv.cs" /> <Compile Include="System\Xml\Xsl\Xslt\QilStrConcatenator.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Scripts.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Stylesheet.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XPathPatternBuilder.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XPathPatternParser.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslAst.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslAstAnalyzer.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslFlags.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XsltInput.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XsltLoader.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XsltQilFactory.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslVisitor.cs" /> <Compile Include="$(CommonPath)System\LocalAppContextSwitches.Common.cs" Link="System\LocalAppContextSwitches.Common.cs" /> <Compile Include="System\Xml\Core\LocalAppContextSwitches.cs" /> <Compile Include="$(CommonPath)System\CSharpHelpers.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.AppendSpanFormattable.cs" Link="Common\System\Text\ValueStringBuilder.AppendSpanFormattable.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="System\Xml\Xsl\Runtime\XmlCollation.Windows.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == ''"> <Compile Include="System\Xml\Xsl\Runtime\XmlCollation.Unix.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImpl.Unix.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <RootNamespace>System.Xml</RootNamespace> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)</TargetFrameworks> <Nullable>enable</Nullable> <EnableRegexGenerator>true</EnableRegexGenerator> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)System\Text\StringBuilderCache.cs" Link="Common\System\StringBuilderCache.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> <Compile Include="System\Xml\BinaryXml\XmlBinaryReader.cs" /> <Compile Include="System\Xml\BinaryXml\BinXmlToken.cs" /> <Compile Include="System\Xml\BinaryXml\SqlUtils.cs" /> <Compile Include="Misc\HResults.cs" /> <Compile Include="System\Xml\AsyncHelper.cs" /> <Compile Include="System\Xml\Base64Decoder.cs" /> <Compile Include="System\Xml\Base64Encoder.cs" /> <Compile Include="System\Xml\Base64EncoderAsync.cs" /> <Compile Include="System\Xml\BinHexDecoder.cs" /> <Compile Include="System\Xml\BinHexEncoder.cs" /> <Compile Include="System\Xml\BinHexEncoderAsync.cs" /> <Compile Include="System\Xml\Bits.cs" /> <Compile Include="System\Xml\BitStack.cs" /> <Compile Include="System\Xml\ByteStack.cs" /> <Compile Include="System\Xml\Core\HtmlEncodedRawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>HtmlEncodedRawTextWriter.tt</DependentUpon> </Compile> <Compile Include="System\Xml\Core\HtmlUtf8RawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>HtmlUtf8RawTextWriter.tt</DependentUpon> </Compile> <Compile Include="System\Xml\Core\TextEncodedRawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>TextEncodedRawTextWriter.tt</DependentUpon> </Compile> <Compile Include="System\Xml\Core\TextUtf8RawTextWriter.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>TextUtf8RawTextWriter.tt</DependentUpon> </Compile> <None Include="System\Xml\Core\HtmlEncodedRawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>HtmlEncodedRawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\HtmlRawTextWriterGenerator.ttinclude" /> <None Include="System\Xml\Core\HtmlUtf8RawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>HtmlUtf8RawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\RawTextWriter.ttinclude" /> <None Include="System\Xml\Core\TextEncodedRawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>TextEncodedRawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\TextRawTextWriterGenerator.ttinclude" /> <None Include="System\Xml\Core\TextUtf8RawTextWriter.tt"> <Generator>TextTemplatingFileGenerator</Generator> <LastGenOutput>TextUtf8RawTextWriter.cs</LastGenOutput> </None> <None Include="System\Xml\Core\XmlRawTextWriterGeneratorAsync.ttinclude" /> <None Include="System\Xml\Core\XmlRawTextWriterGenerator.ttinclude" /> <None Include="System\Xml\Core\RawTextWriterEncoded.ttinclude" /> <Content Include="System\Xml\Core\XmlEncodedRawTextWriter.tt"> <LastGenOutput>XmlEncodedRawTextWriter.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlEncodedRawTextWriter.cs"> <DependentUpon>XmlEncodedRawTextWriter.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <Content Include="System\Xml\Core\XmlEncodedRawTextWriterAsync.tt"> <LastGenOutput>XmlEncodedRawTextWriterAsync.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlEncodedRawTextWriterAsync.cs"> <DependentUpon>XmlEncodedRawTextWriterAsync.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <None Include="System\Xml\Core\RawTextWriterUtf8.ttinclude" /> <Content Include="System\Xml\Core\XmlUtf8RawTextWriter.tt"> <LastGenOutput>XmlUtf8RawTextWriter.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlUtf8RawTextWriter.cs"> <DependentUpon>XmlUtf8RawTextWriter.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <Content Include="System\Xml\Core\XmlUtf8RawTextWriterAsync.tt"> <LastGenOutput>XmlUtf8RawTextWriterAsync.cs</LastGenOutput> <Generator>TextTemplatingFileGenerator</Generator> </Content> <Compile Include="System\Xml\Core\XmlUtf8RawTextWriterAsync.cs"> <DependentUpon>XmlUtf8RawTextWriterAsync.tt</DependentUpon> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> </Compile> <Compile Include="System\Xml\DiagnosticsSwitches.cs" /> <Compile Include="System\Xml\Dom\XmlNamedNodeMap.SmallXmlNodeList.cs" /> <Compile Include="System\Xml\EmptyEnumerator.cs" /> <Compile Include="System\Xml\HWStack.cs" /> <Compile Include="System\Xml\IApplicationResourceStreamResolver.cs" /> <Compile Include="System\Xml\IHasXmlNode.cs" /> <Compile Include="System\Xml\IXmlLineInfo.cs" /> <Compile Include="System\Xml\IXmlNamespaceResolver.cs" /> <Compile Include="System\Xml\LineInfo.cs" /> <Compile Include="System\Xml\MTNameTable.cs" /> <Compile Include="System\Xml\NameTable.cs" /> <Compile Include="System\Xml\Ref.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationEventSource.cs" /> <Compile Include="System\Xml\ValidateNames.cs" /> <Compile Include="System\Xml\XmlCharType.cs" /> <Compile Include="System\Xml\XmlComplianceUtil.cs" /> <Compile Include="System\Xml\XmlConvert.cs" /> <Compile Include="System\Xml\XmlDownloadManager.cs" /> <Compile Include="System\Xml\XmlDownloadManagerAsync.cs" /> <Compile Include="System\Xml\XmlEncoding.cs" /> <Compile Include="System\Xml\XmlException.cs" /> <Compile Include="System\Xml\XmlNamespacemanager.cs" /> <Compile Include="System\Xml\XmlNamespaceScope.cs" /> <Compile Include="System\Xml\XmlNameTable.cs" /> <Compile Include="System\Xml\XmlNodeOrder.cs" /> <Compile Include="System\Xml\XmlNodeType.cs" /> <Compile Include="System\Xml\XmlNullResolver.cs" /> <Compile Include="System\Xml\XmlQualifiedName.cs" /> <Compile Include="System\Xml\XmlReservedNs.cs" /> <Compile Include="System\Xml\XmlResolver.cs" /> <Compile Include="System\Xml\XmlResolverAsync.cs" /> <Compile Include="System\Xml\XmlSecureResolver.cs" /> <Compile Include="System\Xml\XmlSecureResolverAsync.cs" /> <Compile Include="System\Xml\XmlUrlResolver.cs" /> <Compile Include="System\Xml\XmlUrlResolverAsync.cs" /> <Compile Include="System\Xml\Core\CharEntityEncoderFallback.cs" /> <Compile Include="System\Xml\Core\ConformanceLevel.cs" /> <Compile Include="System\Xml\Core\DtdProcessing.cs" /> <Compile Include="System\Xml\Core\EntityHandling.cs" /> <Compile Include="System\Xml\Core\IDtdInfo.cs" /> <Compile Include="System\Xml\Core\IDtdParser.cs" /> <Compile Include="System\Xml\Core\IDtdParserAsync.cs" /> <Compile Include="System\Xml\Core\IDtdParserAdapter.cs" /> <Compile Include="System\Xml\Core\IDtdParserAdapterAsync.cs" /> <Compile Include="System\Xml\Core\IncrementalReadDecoders.cs" /> <Compile Include="System\Xml\Core\IValidationEventHandling.cs" /> <Compile Include="System\Xml\Core\NamespaceHandling.cs" /> <Compile Include="System\Xml\Core\NewLineHandling.cs" /> <Compile Include="System\Xml\Core\IRemovableWriter.cs" /> <Compile Include="System\Xml\Core\QueryOutputWriter.cs" /> <Compile Include="System\Xml\Core\QueryOutputWriterV1.cs" /> <Compile Include="System\Xml\Core\ReadContentAsBinaryHelper.cs" /> <Compile Include="System\Xml\Core\ReadContentAsBinaryHelperAsync.cs" /> <Compile Include="System\Xml\Core\ReadOnlyTernaryTree.cs" /> <Compile Include="System\Xml\Core\ReadState.cs" /> <Compile Include="System\Xml\Core\ValidatingReaderNodeData.cs" /> <Compile Include="System\Xml\Core\ValidationType.cs" /> <Compile Include="System\Xml\Core\WhitespaceHandling.cs" /> <Compile Include="System\Xml\Core\XmlAsyncCheckReader.cs" /> <Compile Include="System\Xml\Core\XmlAsyncCheckWriter.cs" /> <Compile Include="System\Xml\Core\XmlAutoDetectWriter.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingReader.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingWriter.cs" /> <Compile Include="System\Xml\Core\XmlCharCheckingWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlEventCache.cs" /> <Compile Include="System\Xml\Core\XmlParserContext.cs" /> <Compile Include="System\Xml\Core\XmlRawWriter.cs" /> <Compile Include="System\Xml\Core\XmlRawWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlReader.cs" /> <Compile Include="System\Xml\Core\XmlReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlReaderSettings.cs" /> <Compile Include="System\Xml\Core\XmlSpace.cs" /> <Compile Include="System\Xml\Core\XmlSubtreeReader.cs" /> <Compile Include="System\Xml\Core\XmlSubtreeReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlTextEncoder.cs" /> <Compile Include="System\Xml\Core\XmlTextReader.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImpl.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImplAsync.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImplHelpers.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImplHelpersAsync.cs" /> <Compile Include="System\Xml\Core\XmlTextWriter.cs" /> <Compile Include="System\Xml\Core\XmlValidatingReader.cs" /> <Compile Include="System\Xml\Core\XmlValidatingReaderImpl.cs" /> <Compile Include="System\Xml\Core\XmlValidatingReaderImplAsync.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriter.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriterHelpers.cs" /> <Compile Include="System\Xml\Core\XmlWellFormedWriterHelpersAsync.cs" /> <Compile Include="System\Xml\Core\XmlWrappingReader.cs" /> <Compile Include="System\Xml\Core\XmlWrappingReaderAsync.cs" /> <Compile Include="System\Xml\Core\XmlWrappingWriter.cs" /> <Compile Include="System\Xml\Core\XmlWrappingWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlWriter.cs" /> <Compile Include="System\Xml\Core\XmlWriterAsync.cs" /> <Compile Include="System\Xml\Core\XmlWriterSettings.cs" /> <Compile Include="System\Xml\Core\XsdValidatingReader.cs" /> <Compile Include="System\Xml\Core\XsdValidatingReaderAsync.cs" /> <Compile Include="System\Xml\Core\XsdCachingReader.cs" /> <Compile Include="System\Xml\Core\XsdCachingReaderAsync.cs" /> <Compile Include="System\Xml\Dom\DocumentXmlWriter.cs" /> <Compile Include="System\Xml\Dom\DocumentXPathNavigator.cs" /> <Compile Include="System\Xml\Dom\DomNameTable.cs" /> <Compile Include="System\Xml\Dom\XmlAttribute.cs" /> <Compile Include="System\Xml\Dom\XmlAttributeCollection.cs" /> <Compile Include="System\Xml\Dom\XmlCDataSection.cs" /> <Compile Include="System\Xml\Dom\XmlCharacterData.cs" /> <Compile Include="System\Xml\Dom\XmlChildEnumerator.cs" /> <Compile Include="System\Xml\Dom\XmlChildNodes.cs" /> <Compile Include="System\Xml\Dom\XmlComment.cs" /> <Compile Include="System\Xml\Dom\XmlDeclaration.cs" /> <Compile Include="System\Xml\Dom\XmlDocument.cs" /> <Compile Include="System\Xml\Dom\XmlDocumentFragment.cs" /> <Compile Include="System\Xml\Dom\XmlDocumentType.cs" /> <Compile Include="System\Xml\Dom\DocumentSchemaValidator.cs" /> <Compile Include="System\Xml\Dom\XmlDomTextWriter.cs" /> <Compile Include="System\Xml\Dom\XmlElement.cs" /> <Compile Include="System\Xml\Dom\XmlElementList.cs" /> <Compile Include="System\Xml\Dom\XmlEntity.cs" /> <Compile Include="System\Xml\Dom\XmlEntityReference.cs" /> <Compile Include="System\Xml\Dom\XmlEventChangedAction.cs" /> <Compile Include="System\Xml\Dom\XmlImplementation.cs" /> <Compile Include="System\Xml\Dom\XmlLinkedNode.cs" /> <Compile Include="System\Xml\Dom\XmlLoader.cs" /> <Compile Include="System\Xml\Dom\XmlName.cs" /> <Compile Include="System\Xml\Dom\XmlNamedNodemap.cs" /> <Compile Include="System\Xml\Dom\XmlNode.cs" /> <Compile Include="System\Xml\Dom\XmlNodeChangedEventArgs.cs" /> <Compile Include="System\Xml\Dom\XmlNodeChangedEventHandler.cs" /> <Compile Include="System\Xml\Dom\XmlNodeList.cs" /> <Compile Include="System\Xml\Dom\XmlNodeReader.cs" /> <Compile Include="System\Xml\Dom\XmlNotation.cs" /> <Compile Include="System\Xml\Dom\XmlProcessingInstruction.cs" /> <Compile Include="System\Xml\Dom\XmlSignificantWhiteSpace.cs" /> <Compile Include="System\Xml\Dom\XmlText.cs" /> <Compile Include="System\Xml\Dom\XmlUnspecifiedAttribute.cs" /> <Compile Include="System\Xml\Dom\XmlWhitespace.cs" /> <Compile Include="System\Xml\Dom\XPathNodeList.cs" /> <Compile Include="System\Xml\Cache\XPathDocumentBuilder.cs" /> <Compile Include="System\Xml\Cache\XPathDocumentIterator.cs" /> <Compile Include="System\Xml\Cache\XPathDocumentNavigator.cs" /> <Compile Include="System\Xml\Cache\XPathNode.cs" /> <Compile Include="System\Xml\Cache\XPathNodeHelper.cs" /> <Compile Include="System\Xml\Cache\XPathNodeInfoAtom.cs" /> <Compile Include="System\Xml\Resolvers\XmlKnownDtds.cs" /> <Compile Include="System\Xml\Resolvers\XmlPreloadedResolver.cs" /> <Compile Include="System\Xml\Resolvers\XmlPreloadedResolverAsync.cs" /> <Compile Include="System\Xml\XPath\IXPathNavigable.cs" /> <Compile Include="System\Xml\XPath\XPathDocument.cs" /> <Compile Include="System\Xml\XPath\XPathException.cs" /> <Compile Include="System\Xml\XPath\XPathExpr.cs" /> <Compile Include="System\Xml\XPath\XPathItem.cs" /> <Compile Include="System\Xml\XPath\XPathNamespaceScope.cs" /> <Compile Include="System\Xml\XPath\XPathNavigator.cs" /> <Compile Include="System\Xml\XPath\XPathNavigatorKeyComparer.cs" /> <Compile Include="System\Xml\XPath\XPathNavigatorReader.cs" /> <Compile Include="System\Xml\XPath\XPathNodeIterator.cs" /> <Compile Include="System\Xml\XPath\XPathNodeType.cs" /> <Compile Include="System\Xml\XPath\Internal\AbsoluteQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\AstNode.cs" /> <Compile Include="System\Xml\XPath\Internal\AttributeQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Axis.cs" /> <Compile Include="System\Xml\XPath\Internal\BaseAxisQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\BooleanExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\BooleanFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\CacheAxisQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\CacheChildrenQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\CacheOutputQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ChildrenQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ClonableStack.cs" /> <Compile Include="System\Xml\XPath\Internal\CompiledXPathExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\ContextQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DescendantBaseQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DescendantQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DescendantoverDescendantQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\DocumentorderQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\EmptyQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ExtensionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\FunctionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Filter.cs" /> <Compile Include="System\Xml\XPath\Internal\FilterQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\FollowingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\FollSiblingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\ForwardPositionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Function.cs" /> <Compile Include="System\Xml\XPath\Internal\Group.cs" /> <Compile Include="System\Xml\XPath\Internal\GroupQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\IdQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\IteratorFilter.cs" /> <Compile Include="System\Xml\XPath\Internal\Query.cs" /> <Compile Include="System\Xml\XPath\Internal\LogicalExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\MergeFilterQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\NamespaceQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\NodeFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\NumberFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\NumericExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\Operand.cs" /> <Compile Include="System\Xml\XPath\Internal\OperandQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Operator.cs" /> <Compile Include="System\Xml\XPath\Internal\ParentQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\PrecedingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\PreSiblingQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\QueryBuilder.cs" /> <Compile Include="System\Xml\XPath\Internal\UnionExpr.cs" /> <Compile Include="System\Xml\XPath\Internal\ResetableIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\ReversePositionQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Root.cs" /> <Compile Include="System\Xml\XPath\Internal\SortQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\StringFunctions.cs" /> <Compile Include="System\Xml\XPath\Internal\ValueQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\Variable.cs" /> <Compile Include="System\Xml\XPath\Internal\VariableQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathAncestorIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathAncestorQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathArrayIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathAxisIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathChildIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathDescendantIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathEmptyIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathMultyIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathParser.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathScanner.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathSelectionIterator.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathSelfQuery.cs" /> <Compile Include="System\Xml\XPath\Internal\XPathSingletonIterator.cs" /> <Compile Include="System\Xml\Xslt\XslCompiledTransform.cs" /> <Compile Include="System\Xml\Xslt\XsltArgumentList.cs" /> <Compile Include="System\Xml\Xslt\XsltContext.cs" /> <Compile Include="System\Xml\Xslt\XsltException.cs" /> <Compile Include="System\Xml\Xslt\XslTransform.cs" /> <Compile Include="System\Xml\Xslt\XsltSettings.cs" /> <Compile Include="System\Xml\Schema\Asttree.cs" /> <Compile Include="System\Xml\Schema\AutoValidator.cs" /> <Compile Include="System\Xml\Schema\BaseProcessor.cs" /> <Compile Include="System\Xml\Schema\BaseValidator.cs" /> <Compile Include="System\Xml\Schema\BitSet.cs" /> <Compile Include="System\Xml\Schema\Chameleonkey.cs" /> <Compile Include="System\Xml\Schema\CompiledidEntityConstraint.cs" /> <Compile Include="System\Xml\Schema\SchemaSetCompiler.cs" /> <Compile Include="System\Xml\Schema\ConstraintStruct.cs" /> <Compile Include="System\Xml\Schema\ContentValidator.cs" /> <Compile Include="System\Xml\Schema\DataTypeImplementation.cs" /> <Compile Include="System\Xml\Schema\DtdParser.cs" /> <Compile Include="System\Xml\Schema\DtdParserAsync.cs" /> <Compile Include="System\Xml\Schema\DtdValidator.cs" /> <Compile Include="System\Xml\Schema\FacetChecker.cs" /> <Compile Include="System\Xml\Schema\IXmlSchemaInfo.cs" /> <Compile Include="System\Xml\Schema\NamespaceList.cs" /> <Compile Include="System\Xml\Schema\Parser.cs" /> <Compile Include="System\Xml\Schema\ParserAsync.cs" /> <Compile Include="System\Xml\Schema\Preprocessor.cs" /> <Compile Include="System\Xml\Schema\SchemaAttDef.cs" /> <Compile Include="System\Xml\Schema\SchemaBuilder.cs" /> <Compile Include="System\Xml\Schema\SchemaCollectionCompiler.cs" /> <Compile Include="System\Xml\Schema\SchemaCollectionpreProcessor.cs" /> <Compile Include="System\Xml\Schema\SchemaDeclBase.cs" /> <Compile Include="System\Xml\Schema\SchemaElementDecl.cs" /> <Compile Include="System\Xml\Schema\SchemaEntity.cs" /> <Compile Include="System\Xml\Schema\SchemaInfo.cs" /> <Compile Include="System\Xml\Schema\SchemaNames.cs" /> <Compile Include="System\Xml\Schema\SchemaNamespacemanager.cs" /> <Compile Include="System\Xml\Schema\SchemaNotation.cs" /> <Compile Include="System\Xml\Schema\SchemaType.cs" /> <Compile Include="System\Xml\Schema\ValidationEventArgs.cs" /> <Compile Include="System\Xml\Schema\ValidationEventHandler.cs" /> <Compile Include="System\Xml\Schema\ValidationState.cs" /> <Compile Include="System\Xml\Schema\XdrBuilder.cs" /> <Compile Include="System\Xml\Schema\XdrValidator.cs" /> <Compile Include="System\Xml\Schema\XmlAtomicValue.cs" /> <Compile Include="System\Xml\Schema\XmlSchema.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAll.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAnnotated.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAnnotation.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAny.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAnyAttribute.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAppInfo.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAttribute.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAttributeGroup.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaAttributeGroupref.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaChoice.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaCollection.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexContentExtension.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexContentRestriction.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaComplexType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContentModel.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContentProcessing.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaContentType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaDataType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaDerivationMethod.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaDocumentation.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaElement.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaException.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaExternal.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaFacet.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaForm.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaGroup.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaGroupBase.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaGroupRef.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaIdEntityConstraint.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaImport.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaInclude.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaInfo.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaNotation.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaObject.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaObjectCollection.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaObjectTable.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaParticle.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaRedefine.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSequence.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSet.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaCompilationSettings.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleContentExtension.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleContentRestriction.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeContent.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeList.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeRestriction.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSimpleTypeUnion.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaSubstitutionGroup.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaType.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaUse.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaValidationException.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaValidator.cs" /> <Compile Include="System\Xml\Schema\XmlSchemaValidity.cs" /> <Compile Include="System\Xml\Schema\XmlSeverityType.cs" /> <Compile Include="System\Xml\Schema\XmlTokenizedType.cs" /> <Compile Include="System\Xml\Schema\XmlTypeCode.cs" /> <Compile Include="System\Xml\Schema\XmlValueConverter.cs" /> <Compile Include="System\Xml\Schema\XsdBuilder.cs" /> <Compile Include="System\Xml\Schema\XsdDateTime.cs" /> <Compile Include="System\Xml\Schema\XsdDuration.cs" /> <Compile Include="System\Xml\Schema\XsdValidator.cs" /> <Compile Include="System\Xml\Schema\Inference\Infer.cs" /> <Compile Include="System\Xml\Schema\Inference\XmlSchemaInferenceException.cs" /> <Compile Include="System\Xml\Serialization\CodeGenerationoptions.cs" /> <Compile Include="System\Xml\Serialization\CodeGenerator.cs" /> <Compile Include="System\Xml\Serialization\CodeIdentifier.cs" /> <Compile Include="System\Xml\Serialization\CodeIdentifiers.cs" /> <Compile Include="System\Xml\Serialization\Compilation.cs" /> <Compile Include="System\Xml\Serialization\Compiler.cs" /> <Compile Include="System\Xml\Serialization\ContextAwareTables.cs" /> <Compile Include="System\Xml\Serialization\ImportContext.cs" /> <Compile Include="System\Xml\Serialization\indentedWriter.cs" /> <Compile Include="System\Xml\Serialization\IXmlSerializable.cs" /> <Compile Include="System\Xml\Serialization\IXmlTextParser.cs" /> <Compile Include="System\Xml\Serialization\Mappings.cs" /> <Compile Include="System\Xml\Serialization\Models.cs" /> <Compile Include="System\Xml\Serialization\NameTable.cs" /> <Compile Include="System\Xml\Serialization\ReflectionXmlSerializationReader.cs" /> <Compile Include="System\Xml\Serialization\ReflectionXmlSerializationWriter.cs" /> <Compile Include="System\Xml\Serialization\SchemaImporter.cs" /> <Compile Include="System\Xml\Serialization\SchemaObjectWriter.cs" /> <Compile Include="System\Xml\Serialization\SoapAttributeAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapAttributeOverrides.cs" /> <Compile Include="System\Xml\Serialization\SoapAttributes.cs" /> <Compile Include="System\Xml\Serialization\SoapElementAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapEnumAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapIgnoreAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapIncludeAttribute.cs" /> <Compile Include="System\Xml\Serialization\SoapReflectionImporter.cs" /> <Compile Include="System\Xml\Serialization\SoapSchemamember.cs" /> <Compile Include="System\Xml\Serialization\SoapTypeAttribute.cs" /> <Compile Include="System\Xml\Serialization\SourceInfo.cs" /> <Compile Include="System\Xml\Serialization\Types.cs" /> <Compile Include="System\Xml\Serialization\XmlAnyAttributeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlAnyElementAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlAnyElementAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlArrayAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlArrayItemAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlArrayItemAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlAttributeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlAttributeOverrides.cs" /> <Compile Include="System\Xml\Serialization\XmlAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlChoiceIdentifierAttribute.cs" /> <Compile Include="System\Xml\Serialization\Xmlcustomformatter.cs" /> <Compile Include="System\Xml\Serialization\XmlElementAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlElementAttributes.cs" /> <Compile Include="System\Xml\Serialization\XmlEnumAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlIgnoreAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlIncludeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlMapping.cs" /> <Compile Include="System\Xml\Serialization\XmlMemberMapping.cs" /> <Compile Include="System\Xml\Serialization\XmlMembersMapping.cs" /> <Compile Include="System\Xml\Serialization\XmlNamespaceDeclarationsAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlReflectionImporter.cs" /> <Compile Include="System\Xml\Serialization\XmlReflectionMember.cs" /> <Compile Include="System\Xml\Serialization\XmlRootAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemaExporter.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemaImporter.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemaProviderAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlSchemas.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationGeneratedCode.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationILGen.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationReader.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationReaderILGen.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationWriter.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializationWriterILGen.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerAssemblyAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializer.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerFactory.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerNamespaces.cs" /> <Compile Include="System\Xml\Serialization\XmlSerializerVersionAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlTextAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlTypeAttribute.cs" /> <Compile Include="System\Xml\Serialization\XmlTypeMapping.cs" /> <Compile Include="System\Xml\Serialization\_Events.cs" /> <Compile Include="System\Xml\Serialization\TypeExtensions.cs" /> <Compile Include="System\Xml\Serialization\PrimitiveXmlSerializers.cs" /> <Compile Include="System\Xml\Serialization\Configuration\DateTimeSerializationSection.cs" /> <Compile Include="System\Xml\Extensions\ExtensionMethods.cs" /> <Compile Include="System\Xml\Serialization\Globals.cs" /> </ItemGroup> <!-- Embedded DTD files --> <ItemGroup> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml1-strict.dtd"> <LogicalName>xhtml1-strict.dtd</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml1-transitional.dtd"> <LogicalName>xhtml1-transitional.dtd</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml1-frameset.dtd"> <LogicalName>xhtml1-frameset.dtd</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml-lat1.ent"> <LogicalName>xhtml-lat1.ent</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml-special.ent"> <LogicalName>xhtml-special.ent</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\XHTML10\no_comments\xhtml-symbol.ent"> <LogicalName>xhtml-symbol.ent</LogicalName> </EmbeddedResource> <EmbeddedResource Include="Utils\DTDs\RSS091\no_comments\rss-0.91.dtd"> <LogicalName>rss-0.91.dtd</LogicalName> </EmbeddedResource> </ItemGroup> <ItemGroup> <Reference Include="System.Reflection.Emit" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Collections.Specialized" /> <Reference Include="System.Console" /> <Reference Include="System.Diagnostics.TraceSource" /> <Reference Include="System.Diagnostics.Tracing" /> <Reference Include="System.IO.FileSystem" /> <Reference Include="System.Linq.Expressions" /> <Reference Include="System.Memory" /> <Reference Include="System.Net.Http" /> <Reference Include="System.Net.Primitives" /> <Reference Include="System.ObjectModel" /> <Reference Include="System.Reflection.Primitives" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.CompilerServices.Unsafe" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Runtime.Loader" /> <Reference Include="System.Security.Cryptography" /> <Reference Include="System.Security.Cryptography.Algorithms" /> <Reference Include="System.Text.Encoding.Extensions" /> <Reference Include="System.Text.RegularExpressions" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Thread" /> </ItemGroup> <ItemGroup> <Compile Include="System\Xml\Xsl\IlGen\GenerateHelper.cs" /> <Compile Include="System\Xml\Xsl\IlGen\IteratorDescriptor.cs" /> <Compile Include="System\Xml\Xsl\IlGen\OptimizerPatterns.cs" /> <Compile Include="System\Xml\Xsl\IlGen\StaticDataManager.cs" /> <Compile Include="System\Xml\Xsl\IlGen\TailCallAnalyzer.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILAnnotation.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILConstructAnalyzer.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILModule.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILOptimization.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILOptimizerVisitor.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlILTrace.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlIlTypeHelper.cs" /> <Compile Include="System\Xml\Xsl\IlGen\XmlIlVisitor.cs" /> <Compile Include="System\Xml\Xsl\XmlIlGenerator.cs" /> <Compile Include="System\Xml\Xsl\XmlILCommand.cs" /> <Compile Include="System\Xml\Xsl\ISourceLineInfo.cs" /> <Compile Include="System\Xml\Xsl\ListBase.cs" /> <Compile Include="System\Xml\Xsl\Pair.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilBinary.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilChoice.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilCloneVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilDataSource.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilExpression.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilFactory.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilFunction.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilInvoke.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilInvokeEarlyBound.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilInvokeLateBound.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilIterator.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilList.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilLiteral.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilLoop.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilName.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilNode.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilNodeType.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilParameter.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilPatternFactory.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilPatternVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilReference.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilReplaceVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilScopedVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilSortKey.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilStrConcat.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilTargetType.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilTernary.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilTypeChecker.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilUnary.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilValidationVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilVisitor.cs" /> <Compile Include="System\Xml\Xsl\QIL\QilXmlWriter.cs" /> <Compile Include="System\Xml\Xsl\QIL\SerializationHints.cs" /> <Compile Include="System\Xml\Xsl\QIL\SubstitutionList.cs" /> <Compile Include="System\Xml\Xsl\QIL\WhitespaceRule.cs" /> <Compile Include="System\Xml\Xsl\QueryReaderSettings.cs" /> <Compile Include="System\Xml\Xsl\Runtime\ContentIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\DecimalFormatter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\DocumentOrderComparer.cs" /> <Compile Include="System\Xml\Xsl\Runtime\DodSequenceMerge.cs" /> <Compile Include="System\Xml\Xsl\Runtime\EarlyBoundInfo.cs" /> <Compile Include="System\Xml\Xsl\Runtime\NumberFormatter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\RtfNavigator.cs" /> <Compile Include="System\Xml\Xsl\Runtime\SetIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\SiblingIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\StringConcat.cs" /> <Compile Include="System\Xml\Xsl\Runtime\TreeIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\WhitespaceRuleLookup.cs" /> <Compile Include="System\Xml\Xsl\Runtime\WhitespaceRuleReader.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlAggregates.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlAttributeCache.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlCollation.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlExtensionFunction.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlILIndex.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlILStorageConverter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlIterators.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlNavigatorFilter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlNavigatorStack.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryContext.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryOutput.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryRuntime.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQuerySequence.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlQueryStaticData.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlRawWriterWrapper.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlSequenceWriter.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlSortKey.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XmlSortKeyAccumulator.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XslNumber.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XsltConvert.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XsltFunctions.cs" /> <Compile Include="System\Xml\Xsl\Runtime\XsltLibrary.cs" /> <Compile Include="System\Xml\Xsl\SourceLineInfo.cs" /> <Compile Include="System\Xml\Xsl\XmlNodeKindFlags.cs" /> <Compile Include="System\Xml\Xsl\XmlQualifiedNameTest.cs" /> <Compile Include="System\Xml\Xsl\XmlQueryCardinality.cs" /> <Compile Include="System\Xml\Xsl\XmlQueryType.cs" /> <Compile Include="System\Xml\Xsl\XmlQueryTypeFactory.cs" /> <Compile Include="System\Xml\Xsl\XPathConvert.cs" /> <Compile Include="System\Xml\Xsl\XPath\IXpathBuilder.cs" /> <Compile Include="System\Xml\Xsl\XPath\IXPathEnvironment.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathAxis.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathBuilder.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathCompileException.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathContext.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathOperator.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathParser.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathQilFactory.cs" /> <Compile Include="System\Xml\Xsl\XPath\XPathScanner.cs" /> <Compile Include="System\Xml\Xsl\XslException.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Action.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ActionFrame.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ApplyImportsAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ApplyTemplatesAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\AttributeAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\AttributeSetAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Avt.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\AvtEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\BeginEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\BuilderInfo.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CallTemplateAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ChooseAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CommentAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CompiledAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Compiler.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ContainerAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyAttributesAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyCodeAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyNamespacesAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyNodeSetAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\CopyOfAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\DbgCompiler.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\DocumentScope.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ElementAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\EndEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Event.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ForEachAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\HtmlProps.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\IfAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\InputScope.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\InputScopeManager.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\IRecordOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\MessageAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NamespaceDecl.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NameSpaceEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NavigatorInput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NavigatorOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\newinstructionaction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\NumberAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\OutKeywords.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\OutputScope.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\OutputScopeManager.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\PrefixQName.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ProcessingInstructionAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Processor.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ReaderOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\RecordBuilder.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\RootAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\SequentialOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\SortAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\StateMachine.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\StringOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\Stylesheet.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateBaseAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateLookupAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TemplateManager.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextEvent.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextOnlyOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TextOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\TheQuery.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\UseAttributeSetsAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\ValueOfAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\VariableAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\WithParamAction.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\WriterOutput.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\XsltCompileContext.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\XsltDebugger.cs" /> <Compile Include="System\Xml\Xsl\XsltOld\XsltOutput.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Compiler.cs" /> <Compile Include="System\Xml\Xsl\Xslt\CompilerError.cs" /> <Compile Include="System\Xml\Xsl\Xslt\CompilerScopeManager.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Focus.cs" /> <Compile Include="System\Xml\Xsl\Xslt\IErrorHelper.cs" /> <Compile Include="System\Xml\Xsl\Xslt\InvokeGenerator.cs" /> <Compile Include="System\Xml\Xsl\Xslt\KeyMatchBuilder.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Keywords.cs" /> <Compile Include="System\Xml\Xsl\Xslt\MatcherBuilder.cs" /> <Compile Include="System\Xml\Xsl\Xslt\OutputScopeManager.cs" /> <Compile Include="System\Xml\Xsl\Xslt\QilGenerator.cs" /> <Compile Include="System\Xml\Xsl\Xslt\QilGeneratorEnv.cs" /> <Compile Include="System\Xml\Xsl\Xslt\QilStrConcatenator.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Scripts.cs" /> <Compile Include="System\Xml\Xsl\Xslt\Stylesheet.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XPathPatternBuilder.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XPathPatternParser.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslAst.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslAstAnalyzer.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslFlags.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XsltInput.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XsltLoader.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XsltQilFactory.cs" /> <Compile Include="System\Xml\Xsl\Xslt\XslVisitor.cs" /> <Compile Include="$(CommonPath)System\LocalAppContextSwitches.Common.cs" Link="System\LocalAppContextSwitches.Common.cs" /> <Compile Include="System\Xml\Core\LocalAppContextSwitches.cs" /> <Compile Include="$(CommonPath)System\CSharpHelpers.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.AppendSpanFormattable.cs" Link="Common\System\Text\ValueStringBuilder.AppendSpanFormattable.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="System\Xml\Xsl\Runtime\XmlCollation.Windows.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == ''"> <Compile Include="System\Xml\Xsl\Runtime\XmlCollation.Unix.cs" /> <Compile Include="System\Xml\Core\XmlTextReaderImpl.Unix.cs" /> </ItemGroup> </Project>
1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.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.Schema { using System; using System.ComponentModel; using System.Xml.Serialization; using System.Xml.Schema; using System.Xml.XPath; using System.Diagnostics; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Globalization; internal abstract class FacetsChecker { private struct FacetsCompiler { private readonly DatatypeImplementation _datatype; private readonly RestrictionFacets _derivedRestriction; private readonly RestrictionFlags _baseFlags; private readonly RestrictionFlags _baseFixedFlags; private readonly RestrictionFlags _validRestrictionFlags; //Helpers private readonly XmlSchemaDatatype _nonNegativeInt; private readonly XmlSchemaDatatype _builtInType; private readonly XmlTypeCode _builtInEnum; private bool _firstPattern; private StringBuilder? _regStr; private XmlSchemaPatternFacet? _pattern_facet; public FacetsCompiler(DatatypeImplementation baseDatatype, RestrictionFacets restriction) { _firstPattern = true; _regStr = null; _pattern_facet = null; _datatype = baseDatatype; _derivedRestriction = restriction; _baseFlags = _datatype.Restriction != null ? _datatype.Restriction.Flags : 0; _baseFixedFlags = _datatype.Restriction != null ? _datatype.Restriction.FixedFlags : 0; _validRestrictionFlags = _datatype.ValidRestrictionFlags; _nonNegativeInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.NonNegativeInteger).Datatype!; _builtInEnum = !(_datatype is Datatype_union || _datatype is Datatype_List) ? _datatype.TypeCode : 0; _builtInType = (int)_builtInEnum > 0 ? DatatypeImplementation.GetSimpleTypeFromTypeCode(_builtInEnum).Datatype! : _datatype; } internal void CompileLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Length, SR.Sch_LengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.Length, SR.Sch_DupLengthFacet); _derivedRestriction.Length = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_LengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.Length) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.Length, _derivedRestriction.Length)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_LengthGtBaseLength, facet); } } // If the base has the MinLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction!.MinLength > _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } // If the base has the MaxLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction!.MaxLength < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.Length); } internal void CompileMinLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinLength, SR.Sch_MinLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinLength, SR.Sch_DupMinLengthFacet); _derivedRestriction.MinLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MinLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MinLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinLength, _derivedRestriction.MinLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction!.MinLength > _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtBaseMinLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length < _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MinLength); } internal void CompileMaxLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxLength, SR.Sch_MaxLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxLength, SR.Sch_DupMaxLengthFacet); _derivedRestriction.MaxLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MaxLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MaxLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxLength, _derivedRestriction.MaxLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction!.MaxLength < _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxLengthGtBaseMaxLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MaxLength); } internal void CompilePatternFacet(XmlSchemaPatternFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Pattern, SR.Sch_PatternFacetProhibited); if (_firstPattern == true) { _regStr = new StringBuilder(); _regStr.Append('('); _regStr.Append(facet.Value); _pattern_facet = facet; _firstPattern = false; } else { _regStr!.Append(")|("); _regStr.Append(facet.Value); } SetFlag(facet, RestrictionFlags.Pattern); } internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable) { CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited); if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = new ArrayList(); } _derivedRestriction.Enumeration.Add(ParseFacetValue(_datatype, facet, SR.Sch_EnumerationFacetInvalid, nsmgr, nameTable)); SetFlag(facet, RestrictionFlags.Enumeration); } internal void CompileWhitespaceFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_WhiteSpaceFacetProhibited); CheckDupFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_DupWhiteSpaceFacet); if (facet.Value == "preserve") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Preserve; } else if (facet.Value == "replace") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Replace; } else if (facet.Value == "collapse") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Collapse; } else { throw new XmlSchemaException(SR.Sch_InvalidWhiteSpace, facet.Value, facet); } if ((_baseFixedFlags & RestrictionFlags.WhiteSpace) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.WhiteSpace, _derivedRestriction.WhiteSpace)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } //Check base and derived whitespace facets XmlSchemaWhiteSpace baseWhitespace; if ((_baseFlags & RestrictionFlags.WhiteSpace) != 0) { baseWhitespace = _datatype.Restriction!.WhiteSpace; } else { baseWhitespace = _datatype.BuiltInWhitespaceFacet; } if (baseWhitespace == XmlSchemaWhiteSpace.Collapse && (_derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Replace || _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve) ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction1, facet); } if (baseWhitespace == XmlSchemaWhiteSpace.Replace && _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction2, facet); } SetFlag(facet, RestrictionFlags.WhiteSpace); } internal void CompileMaxInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_MaxInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_DupMaxInclusiveFacet); _derivedRestriction.MaxInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxInclusive!, _derivedRestriction.MaxInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxInclusive, facet); SetFlag(facet, RestrictionFlags.MaxInclusive); } internal void CompileMaxExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_MaxExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_DupMaxExclusiveFacet); _derivedRestriction.MaxExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxExclusive!, _derivedRestriction.MaxExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxExclusive, facet); SetFlag(facet, RestrictionFlags.MaxExclusive); } internal void CompileMinInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_MinInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_DupMinInclusiveFacet); _derivedRestriction.MinInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinInclusive!, _derivedRestriction.MinInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinInclusive, facet); SetFlag(facet, RestrictionFlags.MinInclusive); } internal void CompileMinExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_MinExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_DupMinExclusiveFacet); _derivedRestriction.MinExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinExclusive!, _derivedRestriction.MinExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinExclusive, facet); SetFlag(facet, RestrictionFlags.MinExclusive); } internal void CompileTotalDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_TotalDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_DupTotalDigitsFacet); XmlSchemaDatatype positiveInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.PositiveInteger).Datatype!; _derivedRestriction.TotalDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(positiveInt, facet, SR.Sch_TotalDigitsFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.TotalDigits) != 0) { if (_datatype.Restriction!.TotalDigits != _derivedRestriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.TotalDigits) != 0) { if (_derivedRestriction.TotalDigits > _datatype.Restriction!.TotalDigits) { throw new XmlSchemaException(SR.Sch_TotalDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.TotalDigits); } internal void CompileFractionDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_FractionDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_DupFractionDigitsFacet); _derivedRestriction.FractionDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_FractionDigitsFacetInvalid, null, null)); if ((_derivedRestriction.FractionDigits != 0) && (_datatype.TypeCode != XmlTypeCode.Decimal)) { throw new XmlSchemaException(SR.Sch_FractionDigitsFacetInvalid, SR.Sch_FractionDigitsNotOnDecimal, facet); } if ((_baseFixedFlags & RestrictionFlags.FractionDigits) != 0) { if (_datatype.Restriction!.FractionDigits != _derivedRestriction.FractionDigits) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.FractionDigits) != 0) { if (_derivedRestriction.FractionDigits > _datatype.Restriction!.FractionDigits) { throw new XmlSchemaException(SR.Sch_FractionDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.FractionDigits); } internal void FinishFacetCompile() { //Additional check for pattern facet //If facet is XMLSchemaPattern, then the String built inside the loop //needs to be converted to a RegEx if (_firstPattern == false) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = new ArrayList(); } try { _regStr!.Append(')'); string tempStr = _regStr.ToString(); if (tempStr.Contains('|')) { // ordinal compare _regStr.Insert(0, '('); _regStr.Append(')'); } _derivedRestriction.Patterns.Add(new Regex(Preprocess(_regStr.ToString()))); } catch (Exception e) { throw new XmlSchemaException(SR.Sch_PatternFacetInvalid, new string[] { e.Message }, e, _pattern_facet!.SourceUri, _pattern_facet.LineNumber, _pattern_facet.LinePosition, _pattern_facet); } } } private void CheckValue(object value, XmlSchemaFacet facet) { RestrictionFacets? restriction = _datatype.Restriction; switch (facet.FacetType) { case FacetType.MaxInclusive: if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction!.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MaxIncExlMismatch, string.Empty); } } break; case FacetType.MaxExclusive: if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction!.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxExlIncMismatch, string.Empty); } } break; case FacetType.MinInclusive: if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction!.MinInclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction!.MinExclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinIncExlMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MinIncMaxExlMismatch, string.Empty); } } break; case FacetType.MinExclusive: if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction!.MinExclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction!.MinInclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinExlIncMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MinExlMaxExlMismatch, string.Empty); } } break; default: Debug.Fail($"Unexpected facet type {facet.FacetType}"); break; } } internal void CompileFacetCombinations() { //They are not allowed on the same type but allowed on derived types. if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MaxInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MinInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.Length) != 0 && (_derivedRestriction.Flags & (RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0 ) { throw new XmlSchemaException(SR.Sch_LengthAndMinMax, string.Empty); } CopyFacetsFromBaseType(); // Check combinations if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxLength) != 0 ) { if (_derivedRestriction.MinLength > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtMaxLength, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive!, _derivedRestriction.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxInclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive!, _derivedRestriction.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive!, _derivedRestriction.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive!, _derivedRestriction.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxInclusive, string.Empty); } } if ((_derivedRestriction.Flags & (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) == (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) { if (_derivedRestriction.FractionDigits > _derivedRestriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_FractionDigitsGtTotalDigits, string.Empty); } } } private void CopyFacetsFromBaseType() { RestrictionFacets baseRestriction = _datatype.Restriction!; // Copy additional facets from the base type if ( (_derivedRestriction.Flags & RestrictionFlags.Length) == 0 && (_baseFlags & RestrictionFlags.Length) != 0 ) { _derivedRestriction.Length = baseRestriction.Length; SetFlag(RestrictionFlags.Length); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) == 0 && (_baseFlags & RestrictionFlags.MinLength) != 0 ) { _derivedRestriction.MinLength = baseRestriction.MinLength; SetFlag(RestrictionFlags.MinLength); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxLength) == 0 && (_baseFlags & RestrictionFlags.MaxLength) != 0 ) { _derivedRestriction.MaxLength = baseRestriction.MaxLength; SetFlag(RestrictionFlags.MaxLength); } if ((_baseFlags & RestrictionFlags.Pattern) != 0) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = baseRestriction.Patterns; } else { _derivedRestriction.Patterns.AddRange(baseRestriction.Patterns!); } SetFlag(RestrictionFlags.Pattern); } if ((_baseFlags & RestrictionFlags.Enumeration) != 0) { if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = baseRestriction.Enumeration; } SetFlag(RestrictionFlags.Enumeration); } if ( (_derivedRestriction.Flags & RestrictionFlags.WhiteSpace) == 0 && (_baseFlags & RestrictionFlags.WhiteSpace) != 0 ) { _derivedRestriction.WhiteSpace = baseRestriction.WhiteSpace; SetFlag(RestrictionFlags.WhiteSpace); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) == 0 && (_baseFlags & RestrictionFlags.MaxInclusive) != 0 ) { _derivedRestriction.MaxInclusive = baseRestriction.MaxInclusive; SetFlag(RestrictionFlags.MaxInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) == 0 && (_baseFlags & RestrictionFlags.MaxExclusive) != 0 ) { _derivedRestriction.MaxExclusive = baseRestriction.MaxExclusive; SetFlag(RestrictionFlags.MaxExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) == 0 && (_baseFlags & RestrictionFlags.MinInclusive) != 0 ) { _derivedRestriction.MinInclusive = baseRestriction.MinInclusive; SetFlag(RestrictionFlags.MinInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) == 0 && (_baseFlags & RestrictionFlags.MinExclusive) != 0 ) { _derivedRestriction.MinExclusive = baseRestriction.MinExclusive; SetFlag(RestrictionFlags.MinExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.TotalDigits) == 0 && (_baseFlags & RestrictionFlags.TotalDigits) != 0 ) { _derivedRestriction.TotalDigits = baseRestriction.TotalDigits; SetFlag(RestrictionFlags.TotalDigits); } if ( (_derivedRestriction.Flags & RestrictionFlags.FractionDigits) == 0 && (_baseFlags & RestrictionFlags.FractionDigits) != 0 ) { _derivedRestriction.FractionDigits = baseRestriction.FractionDigits; SetFlag(RestrictionFlags.FractionDigits); } } private object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, string code, IXmlNamespaceResolver? nsmgr, XmlNameTable? nameTable) { object? typedValue; Exception? ex = datatype.TryParseValue(facet.Value!, nameTable, nsmgr, out typedValue); if (ex == null) { return typedValue!; } else { throw new XmlSchemaException(code, new string[] { ex.Message }, ex, facet.SourceUri, facet.LineNumber, facet.LinePosition, facet); } } private struct Map { internal Map(char m, string r) { match = m; replacement = r; } internal char match; internal string replacement; }; private static readonly Map[] s_map = { new Map('c', "\\p{_xmlC}"), new Map('C', "\\P{_xmlC}"), new Map('d', "\\p{_xmlD}"), new Map('D', "\\P{_xmlD}"), new Map('i', "\\p{_xmlI}"), new Map('I', "\\P{_xmlI}"), new Map('w', "\\p{_xmlW}"), new Map('W', "\\P{_xmlW}"), }; private static string Preprocess(string pattern) { StringBuilder bufBld = new StringBuilder(); bufBld.Append('^'); char[] source = pattern.ToCharArray(); int length = pattern.Length; int copyPosition = 0; for (int position = 0; position < length - 2; position++) { if (source[position] == '\\') { if (source[position + 1] == '\\') { position++; // skip it } else { char ch = source[position + 1]; for (int i = 0; i < s_map.Length; i++) { if (s_map[i].match == ch) { if (copyPosition < position) { bufBld.Append(source, copyPosition, position - copyPosition); } bufBld.Append(s_map[i].replacement); position++; copyPosition = position + 1; break; } } } } } if (copyPosition < length) { bufBld.Append(source, copyPosition, length - copyPosition); } bufBld.Append('$'); return bufBld.ToString(); } private void CheckProhibitedFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_validRestrictionFlags & flag) == 0) { throw new XmlSchemaException(errorCode, _datatype.TypeCodeString, facet); } } private void CheckDupFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_derivedRestriction.Flags & flag) != 0) { throw new XmlSchemaException(errorCode, facet); } } private void SetFlag(XmlSchemaFacet facet, RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if (facet.IsFixed) { _derivedRestriction.FixedFlags |= flag; } } private void SetFlag(RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if ((_baseFixedFlags & flag) != 0) { _derivedRestriction.FixedFlags |= flag; } } } internal virtual Exception? CheckLexicalFacets(ref string parseString, XmlSchemaDatatype datatype) { CheckWhitespaceFacets(ref parseString, datatype); return CheckPatternFacets(datatype.Restriction, parseString); } internal virtual Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(long value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(int value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(short value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(double value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(float value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { return null; } internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) { // before parsing, check whitespace facet RestrictionFacets? restriction = datatype.Restriction; switch (datatype.Variety) { case XmlSchemaDatatypeVariety.List: s = s.Trim(); break; case XmlSchemaDatatypeVariety.Atomic: if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } else if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction != null && (restriction.Flags & RestrictionFlags.WhiteSpace) != 0) { //Restriction has whitespace facet specified if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } } break; default: break; } } internal Exception? CheckPatternFacets(RestrictionFacets? restriction, string value) { if (restriction != null && (restriction.Flags & RestrictionFlags.Pattern) != 0) { for (int i = 0; i < restriction.Patterns!.Count; ++i) { Regex regex = (Regex)restriction.Patterns[i]!; if (!regex.IsMatch(value)) { return new XmlSchemaException(SR.Sch_PatternConstraintFailed, string.Empty); } } } return null; } internal virtual bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return false; } //Compile-time Facet Checking internal virtual RestrictionFacets ConstructRestriction(DatatypeImplementation datatype, XmlSchemaObjectCollection facets, XmlNameTable nameTable) { //Datatype is the type on which this method is called RestrictionFacets derivedRestriction = new RestrictionFacets(); FacetsCompiler facetCompiler = new FacetsCompiler(datatype, derivedRestriction); for (int i = 0; i < facets.Count; ++i) { XmlSchemaFacet facet = (XmlSchemaFacet)facets[i]; if (facet.Value == null) { throw new XmlSchemaException(SR.Sch_InvalidFacet, facet); } IXmlNamespaceResolver nsmgr = new SchemaNamespaceManager(facet); switch (facet.FacetType) { case FacetType.Length: facetCompiler.CompileLengthFacet(facet); break; case FacetType.MinLength: facetCompiler.CompileMinLengthFacet(facet); break; case FacetType.MaxLength: facetCompiler.CompileMaxLengthFacet(facet); break; case FacetType.Pattern: facetCompiler.CompilePatternFacet((facet as XmlSchemaPatternFacet)!); break; case FacetType.Enumeration: facetCompiler.CompileEnumerationFacet(facet, nsmgr, nameTable); break; case FacetType.Whitespace: facetCompiler.CompileWhitespaceFacet(facet); break; case FacetType.MinInclusive: facetCompiler.CompileMinInclusiveFacet(facet); break; case FacetType.MinExclusive: facetCompiler.CompileMinExclusiveFacet(facet); break; case FacetType.MaxInclusive: facetCompiler.CompileMaxInclusiveFacet(facet); break; case FacetType.MaxExclusive: facetCompiler.CompileMaxExclusiveFacet(facet); break; case FacetType.TotalDigits: facetCompiler.CompileTotalDigitsFacet(facet); break; case FacetType.FractionDigits: facetCompiler.CompileFractionDigitsFacet(facet); break; default: throw new XmlSchemaException(SR.Sch_UnknownFacet, facet); } } facetCompiler.FinishFacetCompile(); facetCompiler.CompileFacetCombinations(); return derivedRestriction; } internal static decimal Power(int x, int y) { //Returns X raised to the power Y decimal returnValue = 1m; decimal decimalValue = (decimal)x; if (y > 28) { //CLR decimal cannot handle more than 29 digits (10 power 28.) return decimal.MaxValue; } for (int i = 0; i < y; i++) { returnValue = returnValue * decimalValue; } return returnValue; } } internal sealed class Numeric10FacetsChecker : FacetsChecker { private readonly decimal _maxValue; private readonly decimal _minValue; internal Numeric10FacetsChecker(decimal minVal, decimal maxVal) { _minValue = minVal; _maxValue = maxVal; } internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { decimal decimalValue = datatype.ValueConverter.ToDecimal(value); return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; //Check built-in facets if (value > _maxValue || value < _minValue) { return new OverflowException(SR.Format(SR.XmlConvert_Overflow, value.ToString(CultureInfo.InvariantCulture), datatype.TypeCodeString)); } //Check user-defined facets if (flags != 0) { Debug.Assert(restriction != null); if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDecimal(restriction.MaxInclusive!)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDecimal(restriction.MaxExclusive!)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < valueConverter.ToDecimal(restriction.MinInclusive!)) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDecimal(restriction.MinExclusive!)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration!, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return CheckTotalAndFractionDigits(value, restriction.TotalDigits, restriction.FractionDigits, ((flags & RestrictionFlags.TotalDigits) != 0), ((flags & RestrictionFlags.FractionDigits) != 0)); } return null; } internal override Exception? CheckValueFacets(long value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(int value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(short value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDecimal(value), enumeration, datatype.ValueConverter); } internal bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDecimal(enumeration[i]!)) { return true; } } return false; } internal Exception? CheckTotalAndFractionDigits(decimal value, int totalDigits, int fractionDigits, bool checkTotal, bool checkFraction) { decimal maxValue = FacetsChecker.Power(10, totalDigits) - 1; //(decimal)Math.Pow(10, totalDigits) - 1 ; int powerCnt = 0; if (value < 0) { value = decimal.Negate(value); //Need to compare maxValue allowed against the absolute value } while (decimal.Truncate(value) != value) { //Till it has a fraction value = value * 10; powerCnt++; } if (checkTotal && (value > maxValue || powerCnt > totalDigits)) { return new XmlSchemaException(SR.Sch_TotalDigitsConstraintFailed, string.Empty); } if (checkFraction && powerCnt > fractionDigits) { return new XmlSchemaException(SR.Sch_FractionDigitsConstraintFailed, string.Empty); } return null; } } internal sealed class Numeric2FacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { double doubleValue = datatype.ValueConverter.ToDouble(value); return CheckValueFacets(doubleValue, datatype); } internal override Exception? CheckValueFacets(double value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDouble(restriction!.MaxInclusive!)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDouble(restriction!.MaxExclusive!)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < (valueConverter.ToDouble(restriction!.MinInclusive!))) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDouble(restriction!.MinExclusive!)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override Exception? CheckValueFacets(float value, XmlSchemaDatatype datatype) { double doubleValue = (double)value; return CheckValueFacets(doubleValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDouble(value), enumeration, datatype.ValueConverter); } private bool MatchEnumeration(double value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDouble(enumeration[i]!)) { return true; } } return false; } } internal sealed class DurationFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { TimeSpan timeSpanValue = (TimeSpan)datatype.ValueConverter.ChangeType(value, typeof(TimeSpan)); return CheckValueFacets(timeSpanValue, datatype); } internal override Exception? CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MaxInclusive!) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MaxExclusive!) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MinInclusive!) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MinExclusive!) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((TimeSpan)value, enumeration); } private bool MatchEnumeration(TimeSpan value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (TimeSpan.Compare(value, (TimeSpan)enumeration[i]!) == 0) { return true; } } return false; } } internal sealed class DateTimeFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { DateTime dateTimeValue = datatype.ValueConverter.ToDateTime(value); return CheckValueFacets(dateTimeValue, datatype); } internal override Exception? CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MaxInclusive!) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MaxExclusive!) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MinInclusive!) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MinExclusive!) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDateTime(value), enumeration, datatype); } private bool MatchEnumeration(DateTime value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (DateTime)enumeration[i]!) == 0) { return true; } } return false; } } internal sealed class StringFacetsChecker : FacetsChecker { //All types derived from string & anyURI private static Regex? s_languagePattern; private static Regex LanguagePattern { get { if (s_languagePattern == null) { Regex langRegex = new Regex("^([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*$"); Interlocked.CompareExchange(ref s_languagePattern, langRegex, null); } return s_languagePattern; } } internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { string stringValue = datatype.ValueConverter.ToString(value); return CheckValueFacets(stringValue, datatype, true); } internal override Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype) { return CheckValueFacets(value, datatype, true); } internal Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype, bool verifyUri) { //Length, MinLength, MaxLength int length = value.Length; RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; Exception? exception; exception = CheckBuiltInFacets(value, datatype.TypeCode, verifyUri); if (exception != null) return exception; if (flags != 0) { if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToString(value), enumeration, datatype); } private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaDatatype datatype) { if (datatype.TypeCode == XmlTypeCode.AnyUri) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals(((Uri)enumeration[i]!).OriginalString)) { return true; } } } else { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((string)enumeration[i]!)) { return true; } } } return false; } private Exception? CheckBuiltInFacets(string s, XmlTypeCode typeCode, bool verifyUri) { Exception? exception = null; switch (typeCode) { case XmlTypeCode.AnyUri: if (verifyUri) { exception = XmlConvert.TryToUri(s, out _); } break; case XmlTypeCode.NormalizedString: exception = XmlConvert.TryVerifyNormalizedString(s); break; case XmlTypeCode.Token: exception = XmlConvert.TryVerifyTOKEN(s); break; case XmlTypeCode.Language: if (s == null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } if (!LanguagePattern.IsMatch(s)) { return new XmlSchemaException(SR.Sch_InvalidLanguageId, string.Empty); } break; case XmlTypeCode.NmToken: exception = XmlConvert.TryVerifyNMTOKEN(s); break; case XmlTypeCode.Name: exception = XmlConvert.TryVerifyName(s); break; case XmlTypeCode.NCName: case XmlTypeCode.Id: case XmlTypeCode.Idref: case XmlTypeCode.Entity: exception = XmlConvert.TryVerifyNCName(s); break; default: break; } return exception; } } internal sealed class QNameFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { XmlQualifiedName qualifiedNameValue = (XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)); return CheckValueFacets(qualifiedNameValue, datatype); } internal override Exception? CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { Debug.Assert(restriction != null); // If there are facets defined string strValue = value.ToString(); int length = strValue.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration!)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)), enumeration); } private bool MatchEnumeration(XmlQualifiedName value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((XmlQualifiedName)enumeration[i]!)) { return true; } } return false; } } internal sealed class MiscFacetsChecker : FacetsChecker { //For bool, anySimpleType } internal sealed class BinaryFacetsChecker : FacetsChecker { //hexBinary & Base64Binary internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { byte[] byteArrayValue = (byte[])value; return CheckValueFacets(byteArrayValue, datatype); } internal override Exception? CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { //Length, MinLength, MaxLength RestrictionFacets? restriction = datatype.Restriction; int length = value.Length; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { //if it has facets defined if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((byte[])value, enumeration, datatype); } private bool MatchEnumeration(byte[] value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (byte[])enumeration[i]!) == 0) { return true; } } return false; } } internal sealed class ListFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { // Check for facets allowed on lists - Length, MinLength, MaxLength Array values = (value as Array)!; Debug.Assert(values != null); RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & (RestrictionFlags.Length | RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0) { int length = values.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { Array values = (value as Array)!; Datatype_List list = (datatype as Datatype_List)!; Debug.Assert(list != null); for (int j = 0; j < values.Length; ++j) { bool found = false; for (int i = 0; i < enumeration.Count; ++i) { Array enumValue = (enumeration[i] as Array)!; Debug.Assert(enumValue != null); if (list.ItemType.Compare(values.GetValue(j)!, enumValue.GetValue(0)!) == 0) { found = true; break; } } if (!found) { return false; } } return true; } } internal sealed class UnionFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, enumeration[i]!) == 0) { // Compare on Datatype_union will compare two XsdSimpleValue return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Schema { using System; using System.ComponentModel; using System.Xml.Serialization; using System.Xml.Schema; using System.Xml.XPath; using System.Diagnostics; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Globalization; internal abstract class FacetsChecker { private struct FacetsCompiler { private readonly DatatypeImplementation _datatype; private readonly RestrictionFacets _derivedRestriction; private readonly RestrictionFlags _baseFlags; private readonly RestrictionFlags _baseFixedFlags; private readonly RestrictionFlags _validRestrictionFlags; //Helpers private readonly XmlSchemaDatatype _nonNegativeInt; private readonly XmlSchemaDatatype _builtInType; private readonly XmlTypeCode _builtInEnum; private bool _firstPattern; private StringBuilder? _regStr; private XmlSchemaPatternFacet? _pattern_facet; public FacetsCompiler(DatatypeImplementation baseDatatype, RestrictionFacets restriction) { _firstPattern = true; _regStr = null; _pattern_facet = null; _datatype = baseDatatype; _derivedRestriction = restriction; _baseFlags = _datatype.Restriction != null ? _datatype.Restriction.Flags : 0; _baseFixedFlags = _datatype.Restriction != null ? _datatype.Restriction.FixedFlags : 0; _validRestrictionFlags = _datatype.ValidRestrictionFlags; _nonNegativeInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.NonNegativeInteger).Datatype!; _builtInEnum = !(_datatype is Datatype_union || _datatype is Datatype_List) ? _datatype.TypeCode : 0; _builtInType = (int)_builtInEnum > 0 ? DatatypeImplementation.GetSimpleTypeFromTypeCode(_builtInEnum).Datatype! : _datatype; } internal void CompileLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Length, SR.Sch_LengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.Length, SR.Sch_DupLengthFacet); _derivedRestriction.Length = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_LengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.Length) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.Length, _derivedRestriction.Length)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_LengthGtBaseLength, facet); } } // If the base has the MinLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction!.MinLength > _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } // If the base has the MaxLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction!.MaxLength < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.Length); } internal void CompileMinLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinLength, SR.Sch_MinLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinLength, SR.Sch_DupMinLengthFacet); _derivedRestriction.MinLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MinLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MinLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinLength, _derivedRestriction.MinLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction!.MinLength > _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtBaseMinLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length < _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MinLength); } internal void CompileMaxLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxLength, SR.Sch_MaxLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxLength, SR.Sch_DupMaxLengthFacet); _derivedRestriction.MaxLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MaxLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MaxLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxLength, _derivedRestriction.MaxLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction!.MaxLength < _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxLengthGtBaseMaxLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MaxLength); } internal void CompilePatternFacet(XmlSchemaPatternFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Pattern, SR.Sch_PatternFacetProhibited); if (_firstPattern == true) { _regStr = new StringBuilder(); _regStr.Append('('); _regStr.Append(facet.Value); _pattern_facet = facet; _firstPattern = false; } else { _regStr!.Append(")|("); _regStr.Append(facet.Value); } SetFlag(facet, RestrictionFlags.Pattern); } internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable) { CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited); if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = new ArrayList(); } _derivedRestriction.Enumeration.Add(ParseFacetValue(_datatype, facet, SR.Sch_EnumerationFacetInvalid, nsmgr, nameTable)); SetFlag(facet, RestrictionFlags.Enumeration); } internal void CompileWhitespaceFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_WhiteSpaceFacetProhibited); CheckDupFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_DupWhiteSpaceFacet); if (facet.Value == "preserve") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Preserve; } else if (facet.Value == "replace") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Replace; } else if (facet.Value == "collapse") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Collapse; } else { throw new XmlSchemaException(SR.Sch_InvalidWhiteSpace, facet.Value, facet); } if ((_baseFixedFlags & RestrictionFlags.WhiteSpace) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.WhiteSpace, _derivedRestriction.WhiteSpace)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } //Check base and derived whitespace facets XmlSchemaWhiteSpace baseWhitespace; if ((_baseFlags & RestrictionFlags.WhiteSpace) != 0) { baseWhitespace = _datatype.Restriction!.WhiteSpace; } else { baseWhitespace = _datatype.BuiltInWhitespaceFacet; } if (baseWhitespace == XmlSchemaWhiteSpace.Collapse && (_derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Replace || _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve) ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction1, facet); } if (baseWhitespace == XmlSchemaWhiteSpace.Replace && _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction2, facet); } SetFlag(facet, RestrictionFlags.WhiteSpace); } internal void CompileMaxInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_MaxInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_DupMaxInclusiveFacet); _derivedRestriction.MaxInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxInclusive!, _derivedRestriction.MaxInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxInclusive, facet); SetFlag(facet, RestrictionFlags.MaxInclusive); } internal void CompileMaxExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_MaxExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_DupMaxExclusiveFacet); _derivedRestriction.MaxExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxExclusive!, _derivedRestriction.MaxExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxExclusive, facet); SetFlag(facet, RestrictionFlags.MaxExclusive); } internal void CompileMinInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_MinInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_DupMinInclusiveFacet); _derivedRestriction.MinInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinInclusive!, _derivedRestriction.MinInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinInclusive, facet); SetFlag(facet, RestrictionFlags.MinInclusive); } internal void CompileMinExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_MinExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_DupMinExclusiveFacet); _derivedRestriction.MinExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinExclusive!, _derivedRestriction.MinExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinExclusive, facet); SetFlag(facet, RestrictionFlags.MinExclusive); } internal void CompileTotalDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_TotalDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_DupTotalDigitsFacet); XmlSchemaDatatype positiveInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.PositiveInteger).Datatype!; _derivedRestriction.TotalDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(positiveInt, facet, SR.Sch_TotalDigitsFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.TotalDigits) != 0) { if (_datatype.Restriction!.TotalDigits != _derivedRestriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.TotalDigits) != 0) { if (_derivedRestriction.TotalDigits > _datatype.Restriction!.TotalDigits) { throw new XmlSchemaException(SR.Sch_TotalDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.TotalDigits); } internal void CompileFractionDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_FractionDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_DupFractionDigitsFacet); _derivedRestriction.FractionDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_FractionDigitsFacetInvalid, null, null)); if ((_derivedRestriction.FractionDigits != 0) && (_datatype.TypeCode != XmlTypeCode.Decimal)) { throw new XmlSchemaException(SR.Sch_FractionDigitsFacetInvalid, SR.Sch_FractionDigitsNotOnDecimal, facet); } if ((_baseFixedFlags & RestrictionFlags.FractionDigits) != 0) { if (_datatype.Restriction!.FractionDigits != _derivedRestriction.FractionDigits) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.FractionDigits) != 0) { if (_derivedRestriction.FractionDigits > _datatype.Restriction!.FractionDigits) { throw new XmlSchemaException(SR.Sch_FractionDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.FractionDigits); } internal void FinishFacetCompile() { //Additional check for pattern facet //If facet is XMLSchemaPattern, then the String built inside the loop //needs to be converted to a RegEx if (_firstPattern == false) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = new ArrayList(); } try { _regStr!.Append(')'); string tempStr = _regStr.ToString(); if (tempStr.Contains('|')) { // ordinal compare _regStr.Insert(0, '('); _regStr.Append(')'); } _derivedRestriction.Patterns.Add(new Regex(Preprocess(_regStr.ToString()))); } catch (Exception e) { throw new XmlSchemaException(SR.Sch_PatternFacetInvalid, new string[] { e.Message }, e, _pattern_facet!.SourceUri, _pattern_facet.LineNumber, _pattern_facet.LinePosition, _pattern_facet); } } } private void CheckValue(object value, XmlSchemaFacet facet) { RestrictionFacets? restriction = _datatype.Restriction; switch (facet.FacetType) { case FacetType.MaxInclusive: if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction!.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MaxIncExlMismatch, string.Empty); } } break; case FacetType.MaxExclusive: if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction!.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxExlIncMismatch, string.Empty); } } break; case FacetType.MinInclusive: if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction!.MinInclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction!.MinExclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinIncExlMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MinIncMaxExlMismatch, string.Empty); } } break; case FacetType.MinExclusive: if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction!.MinExclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction!.MinInclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinExlIncMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MinExlMaxExlMismatch, string.Empty); } } break; default: Debug.Fail($"Unexpected facet type {facet.FacetType}"); break; } } internal void CompileFacetCombinations() { //They are not allowed on the same type but allowed on derived types. if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MaxInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MinInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.Length) != 0 && (_derivedRestriction.Flags & (RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0 ) { throw new XmlSchemaException(SR.Sch_LengthAndMinMax, string.Empty); } CopyFacetsFromBaseType(); // Check combinations if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxLength) != 0 ) { if (_derivedRestriction.MinLength > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtMaxLength, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive!, _derivedRestriction.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxInclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive!, _derivedRestriction.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive!, _derivedRestriction.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive!, _derivedRestriction.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxInclusive, string.Empty); } } if ((_derivedRestriction.Flags & (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) == (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) { if (_derivedRestriction.FractionDigits > _derivedRestriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_FractionDigitsGtTotalDigits, string.Empty); } } } private void CopyFacetsFromBaseType() { RestrictionFacets baseRestriction = _datatype.Restriction!; // Copy additional facets from the base type if ( (_derivedRestriction.Flags & RestrictionFlags.Length) == 0 && (_baseFlags & RestrictionFlags.Length) != 0 ) { _derivedRestriction.Length = baseRestriction.Length; SetFlag(RestrictionFlags.Length); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) == 0 && (_baseFlags & RestrictionFlags.MinLength) != 0 ) { _derivedRestriction.MinLength = baseRestriction.MinLength; SetFlag(RestrictionFlags.MinLength); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxLength) == 0 && (_baseFlags & RestrictionFlags.MaxLength) != 0 ) { _derivedRestriction.MaxLength = baseRestriction.MaxLength; SetFlag(RestrictionFlags.MaxLength); } if ((_baseFlags & RestrictionFlags.Pattern) != 0) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = baseRestriction.Patterns; } else { _derivedRestriction.Patterns.AddRange(baseRestriction.Patterns!); } SetFlag(RestrictionFlags.Pattern); } if ((_baseFlags & RestrictionFlags.Enumeration) != 0) { if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = baseRestriction.Enumeration; } SetFlag(RestrictionFlags.Enumeration); } if ( (_derivedRestriction.Flags & RestrictionFlags.WhiteSpace) == 0 && (_baseFlags & RestrictionFlags.WhiteSpace) != 0 ) { _derivedRestriction.WhiteSpace = baseRestriction.WhiteSpace; SetFlag(RestrictionFlags.WhiteSpace); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) == 0 && (_baseFlags & RestrictionFlags.MaxInclusive) != 0 ) { _derivedRestriction.MaxInclusive = baseRestriction.MaxInclusive; SetFlag(RestrictionFlags.MaxInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) == 0 && (_baseFlags & RestrictionFlags.MaxExclusive) != 0 ) { _derivedRestriction.MaxExclusive = baseRestriction.MaxExclusive; SetFlag(RestrictionFlags.MaxExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) == 0 && (_baseFlags & RestrictionFlags.MinInclusive) != 0 ) { _derivedRestriction.MinInclusive = baseRestriction.MinInclusive; SetFlag(RestrictionFlags.MinInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) == 0 && (_baseFlags & RestrictionFlags.MinExclusive) != 0 ) { _derivedRestriction.MinExclusive = baseRestriction.MinExclusive; SetFlag(RestrictionFlags.MinExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.TotalDigits) == 0 && (_baseFlags & RestrictionFlags.TotalDigits) != 0 ) { _derivedRestriction.TotalDigits = baseRestriction.TotalDigits; SetFlag(RestrictionFlags.TotalDigits); } if ( (_derivedRestriction.Flags & RestrictionFlags.FractionDigits) == 0 && (_baseFlags & RestrictionFlags.FractionDigits) != 0 ) { _derivedRestriction.FractionDigits = baseRestriction.FractionDigits; SetFlag(RestrictionFlags.FractionDigits); } } private object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, string code, IXmlNamespaceResolver? nsmgr, XmlNameTable? nameTable) { object? typedValue; Exception? ex = datatype.TryParseValue(facet.Value!, nameTable, nsmgr, out typedValue); if (ex == null) { return typedValue!; } else { throw new XmlSchemaException(code, new string[] { ex.Message }, ex, facet.SourceUri, facet.LineNumber, facet.LinePosition, facet); } } private struct Map { internal Map(char m, string r) { match = m; replacement = r; } internal char match; internal string replacement; }; private static readonly Map[] s_map = { new Map('c', "\\p{_xmlC}"), new Map('C', "\\P{_xmlC}"), new Map('d', "\\p{_xmlD}"), new Map('D', "\\P{_xmlD}"), new Map('i', "\\p{_xmlI}"), new Map('I', "\\P{_xmlI}"), new Map('w', "\\p{_xmlW}"), new Map('W', "\\P{_xmlW}"), }; private static string Preprocess(string pattern) { StringBuilder bufBld = new StringBuilder(); bufBld.Append('^'); char[] source = pattern.ToCharArray(); int length = pattern.Length; int copyPosition = 0; for (int position = 0; position < length - 2; position++) { if (source[position] == '\\') { if (source[position + 1] == '\\') { position++; // skip it } else { char ch = source[position + 1]; for (int i = 0; i < s_map.Length; i++) { if (s_map[i].match == ch) { if (copyPosition < position) { bufBld.Append(source, copyPosition, position - copyPosition); } bufBld.Append(s_map[i].replacement); position++; copyPosition = position + 1; break; } } } } } if (copyPosition < length) { bufBld.Append(source, copyPosition, length - copyPosition); } bufBld.Append('$'); return bufBld.ToString(); } private void CheckProhibitedFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_validRestrictionFlags & flag) == 0) { throw new XmlSchemaException(errorCode, _datatype.TypeCodeString, facet); } } private void CheckDupFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_derivedRestriction.Flags & flag) != 0) { throw new XmlSchemaException(errorCode, facet); } } private void SetFlag(XmlSchemaFacet facet, RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if (facet.IsFixed) { _derivedRestriction.FixedFlags |= flag; } } private void SetFlag(RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if ((_baseFixedFlags & flag) != 0) { _derivedRestriction.FixedFlags |= flag; } } } internal virtual Exception? CheckLexicalFacets(ref string parseString, XmlSchemaDatatype datatype) { CheckWhitespaceFacets(ref parseString, datatype); return CheckPatternFacets(datatype.Restriction, parseString); } internal virtual Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(long value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(int value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(short value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(double value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(float value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { return null; } internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) { // before parsing, check whitespace facet RestrictionFacets? restriction = datatype.Restriction; switch (datatype.Variety) { case XmlSchemaDatatypeVariety.List: s = s.Trim(); break; case XmlSchemaDatatypeVariety.Atomic: if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } else if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction != null && (restriction.Flags & RestrictionFlags.WhiteSpace) != 0) { //Restriction has whitespace facet specified if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } } break; default: break; } } internal Exception? CheckPatternFacets(RestrictionFacets? restriction, string value) { if (restriction != null && (restriction.Flags & RestrictionFlags.Pattern) != 0) { for (int i = 0; i < restriction.Patterns!.Count; ++i) { Regex regex = (Regex)restriction.Patterns[i]!; if (!regex.IsMatch(value)) { return new XmlSchemaException(SR.Sch_PatternConstraintFailed, string.Empty); } } } return null; } internal virtual bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return false; } //Compile-time Facet Checking internal virtual RestrictionFacets ConstructRestriction(DatatypeImplementation datatype, XmlSchemaObjectCollection facets, XmlNameTable nameTable) { //Datatype is the type on which this method is called RestrictionFacets derivedRestriction = new RestrictionFacets(); FacetsCompiler facetCompiler = new FacetsCompiler(datatype, derivedRestriction); for (int i = 0; i < facets.Count; ++i) { XmlSchemaFacet facet = (XmlSchemaFacet)facets[i]; if (facet.Value == null) { throw new XmlSchemaException(SR.Sch_InvalidFacet, facet); } IXmlNamespaceResolver nsmgr = new SchemaNamespaceManager(facet); switch (facet.FacetType) { case FacetType.Length: facetCompiler.CompileLengthFacet(facet); break; case FacetType.MinLength: facetCompiler.CompileMinLengthFacet(facet); break; case FacetType.MaxLength: facetCompiler.CompileMaxLengthFacet(facet); break; case FacetType.Pattern: facetCompiler.CompilePatternFacet((facet as XmlSchemaPatternFacet)!); break; case FacetType.Enumeration: facetCompiler.CompileEnumerationFacet(facet, nsmgr, nameTable); break; case FacetType.Whitespace: facetCompiler.CompileWhitespaceFacet(facet); break; case FacetType.MinInclusive: facetCompiler.CompileMinInclusiveFacet(facet); break; case FacetType.MinExclusive: facetCompiler.CompileMinExclusiveFacet(facet); break; case FacetType.MaxInclusive: facetCompiler.CompileMaxInclusiveFacet(facet); break; case FacetType.MaxExclusive: facetCompiler.CompileMaxExclusiveFacet(facet); break; case FacetType.TotalDigits: facetCompiler.CompileTotalDigitsFacet(facet); break; case FacetType.FractionDigits: facetCompiler.CompileFractionDigitsFacet(facet); break; default: throw new XmlSchemaException(SR.Sch_UnknownFacet, facet); } } facetCompiler.FinishFacetCompile(); facetCompiler.CompileFacetCombinations(); return derivedRestriction; } internal static decimal Power(int x, int y) { //Returns X raised to the power Y decimal returnValue = 1m; decimal decimalValue = (decimal)x; if (y > 28) { //CLR decimal cannot handle more than 29 digits (10 power 28.) return decimal.MaxValue; } for (int i = 0; i < y; i++) { returnValue = returnValue * decimalValue; } return returnValue; } } internal sealed class Numeric10FacetsChecker : FacetsChecker { private readonly decimal _maxValue; private readonly decimal _minValue; internal Numeric10FacetsChecker(decimal minVal, decimal maxVal) { _minValue = minVal; _maxValue = maxVal; } internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { decimal decimalValue = datatype.ValueConverter.ToDecimal(value); return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; //Check built-in facets if (value > _maxValue || value < _minValue) { return new OverflowException(SR.Format(SR.XmlConvert_Overflow, value.ToString(CultureInfo.InvariantCulture), datatype.TypeCodeString)); } //Check user-defined facets if (flags != 0) { Debug.Assert(restriction != null); if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDecimal(restriction.MaxInclusive!)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDecimal(restriction.MaxExclusive!)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < valueConverter.ToDecimal(restriction.MinInclusive!)) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDecimal(restriction.MinExclusive!)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration!, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return CheckTotalAndFractionDigits(value, restriction.TotalDigits, restriction.FractionDigits, ((flags & RestrictionFlags.TotalDigits) != 0), ((flags & RestrictionFlags.FractionDigits) != 0)); } return null; } internal override Exception? CheckValueFacets(long value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(int value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(short value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDecimal(value), enumeration, datatype.ValueConverter); } internal bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDecimal(enumeration[i]!)) { return true; } } return false; } internal Exception? CheckTotalAndFractionDigits(decimal value, int totalDigits, int fractionDigits, bool checkTotal, bool checkFraction) { decimal maxValue = FacetsChecker.Power(10, totalDigits) - 1; //(decimal)Math.Pow(10, totalDigits) - 1 ; int powerCnt = 0; if (value < 0) { value = decimal.Negate(value); //Need to compare maxValue allowed against the absolute value } while (decimal.Truncate(value) != value) { //Till it has a fraction value = value * 10; powerCnt++; } if (checkTotal && (value > maxValue || powerCnt > totalDigits)) { return new XmlSchemaException(SR.Sch_TotalDigitsConstraintFailed, string.Empty); } if (checkFraction && powerCnt > fractionDigits) { return new XmlSchemaException(SR.Sch_FractionDigitsConstraintFailed, string.Empty); } return null; } } internal sealed class Numeric2FacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { double doubleValue = datatype.ValueConverter.ToDouble(value); return CheckValueFacets(doubleValue, datatype); } internal override Exception? CheckValueFacets(double value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDouble(restriction!.MaxInclusive!)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDouble(restriction!.MaxExclusive!)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < (valueConverter.ToDouble(restriction!.MinInclusive!))) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDouble(restriction!.MinExclusive!)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override Exception? CheckValueFacets(float value, XmlSchemaDatatype datatype) { double doubleValue = (double)value; return CheckValueFacets(doubleValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDouble(value), enumeration, datatype.ValueConverter); } private bool MatchEnumeration(double value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDouble(enumeration[i]!)) { return true; } } return false; } } internal sealed class DurationFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { TimeSpan timeSpanValue = (TimeSpan)datatype.ValueConverter.ChangeType(value, typeof(TimeSpan)); return CheckValueFacets(timeSpanValue, datatype); } internal override Exception? CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MaxInclusive!) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MaxExclusive!) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MinInclusive!) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MinExclusive!) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((TimeSpan)value, enumeration); } private bool MatchEnumeration(TimeSpan value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (TimeSpan.Compare(value, (TimeSpan)enumeration[i]!) == 0) { return true; } } return false; } } internal sealed class DateTimeFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { DateTime dateTimeValue = datatype.ValueConverter.ToDateTime(value); return CheckValueFacets(dateTimeValue, datatype); } internal override Exception? CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MaxInclusive!) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MaxExclusive!) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MinInclusive!) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MinExclusive!) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDateTime(value), enumeration, datatype); } private bool MatchEnumeration(DateTime value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (DateTime)enumeration[i]!) == 0) { return true; } } return false; } } internal sealed partial class StringFacetsChecker : FacetsChecker { //All types derived from string & anyURI [RegexGenerator("^([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*$", RegexOptions.ExplicitCapture)] private static partial Regex LanguageRegex(); internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { string stringValue = datatype.ValueConverter.ToString(value); return CheckValueFacets(stringValue, datatype, true); } internal override Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype) { return CheckValueFacets(value, datatype, true); } internal Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype, bool verifyUri) { //Length, MinLength, MaxLength int length = value.Length; RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; Exception? exception; exception = CheckBuiltInFacets(value, datatype.TypeCode, verifyUri); if (exception != null) return exception; if (flags != 0) { if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToString(value), enumeration, datatype); } private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaDatatype datatype) { if (datatype.TypeCode == XmlTypeCode.AnyUri) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals(((Uri)enumeration[i]!).OriginalString)) { return true; } } } else { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((string)enumeration[i]!)) { return true; } } } return false; } private Exception? CheckBuiltInFacets(string s, XmlTypeCode typeCode, bool verifyUri) { Exception? exception = null; switch (typeCode) { case XmlTypeCode.AnyUri: if (verifyUri) { exception = XmlConvert.TryToUri(s, out _); } break; case XmlTypeCode.NormalizedString: exception = XmlConvert.TryVerifyNormalizedString(s); break; case XmlTypeCode.Token: exception = XmlConvert.TryVerifyTOKEN(s); break; case XmlTypeCode.Language: if (s == null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } if (!LanguageRegex().IsMatch(s)) { return new XmlSchemaException(SR.Sch_InvalidLanguageId, string.Empty); } break; case XmlTypeCode.NmToken: exception = XmlConvert.TryVerifyNMTOKEN(s); break; case XmlTypeCode.Name: exception = XmlConvert.TryVerifyName(s); break; case XmlTypeCode.NCName: case XmlTypeCode.Id: case XmlTypeCode.Idref: case XmlTypeCode.Entity: exception = XmlConvert.TryVerifyNCName(s); break; default: break; } return exception; } } internal sealed class QNameFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { XmlQualifiedName qualifiedNameValue = (XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)); return CheckValueFacets(qualifiedNameValue, datatype); } internal override Exception? CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { Debug.Assert(restriction != null); // If there are facets defined string strValue = value.ToString(); int length = strValue.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration!)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)), enumeration); } private bool MatchEnumeration(XmlQualifiedName value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((XmlQualifiedName)enumeration[i]!)) { return true; } } return false; } } internal sealed class MiscFacetsChecker : FacetsChecker { //For bool, anySimpleType } internal sealed class BinaryFacetsChecker : FacetsChecker { //hexBinary & Base64Binary internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { byte[] byteArrayValue = (byte[])value; return CheckValueFacets(byteArrayValue, datatype); } internal override Exception? CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { //Length, MinLength, MaxLength RestrictionFacets? restriction = datatype.Restriction; int length = value.Length; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { //if it has facets defined if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((byte[])value, enumeration, datatype); } private bool MatchEnumeration(byte[] value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (byte[])enumeration[i]!) == 0) { return true; } } return false; } } internal sealed class ListFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { // Check for facets allowed on lists - Length, MinLength, MaxLength Array values = (value as Array)!; Debug.Assert(values != null); RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & (RestrictionFlags.Length | RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0) { int length = values.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { Array values = (value as Array)!; Datatype_List list = (datatype as Datatype_List)!; Debug.Assert(list != null); for (int j = 0; j < values.Length; ++j) { bool found = false; for (int i = 0; i < enumeration.Count; ++i) { Array enumValue = (enumeration[i] as Array)!; Debug.Assert(enumValue != null); if (list.ItemType.Compare(values.GetValue(j)!, enumValue.GetValue(0)!) == 0) { found = true; break; } } if (!found) { return false; } } return true; } } internal sealed class UnionFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, enumeration[i]!) == 0) { // Compare on Datatype_union will compare two XsdSimpleValue return true; } } return false; } } }
1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Xml.Extensions; namespace System.Xml.Serialization { internal sealed class SourceInfo { //a[ia] //((global::System.Xml.Serialization.XmlSerializerNamespaces)p[0]) private static readonly Regex s_regex = new Regex("([(][(](?<t>[^)]+)[)])?(?<a>[^[]+)[[](?<ia>.+)[]][)]?"); //((global::Microsoft.CFx.Test.Common.TypeLibrary.IXSType_9)o), @"IXSType_9", @"", true, true); private static readonly Regex s_regex2 = new Regex("[(][(](?<cast>[^)]+)[)](?<arg>[^)]+)[)]"); private static readonly Lazy<MethodInfo> s_iListGetItemMethod = new Lazy<MethodInfo>( () => { return typeof(IList).GetMethod( "get_Item", new Type[] { typeof(int) } )!; }); public string Source; public readonly string Arg; public readonly MemberInfo? MemberInfo; [DynamicallyAccessedMembers(TrimmerConstants.AllMethods)] public readonly Type? Type; public readonly CodeGenerator ILG; public SourceInfo(string source, string? arg, MemberInfo? memberInfo, [DynamicallyAccessedMembers(TrimmerConstants.AllMethods)] Type? type, CodeGenerator ilg) { this.Source = source; this.Arg = arg ?? source; this.MemberInfo = memberInfo; this.Type = type; this.ILG = ilg; } public SourceInfo CastTo(TypeDesc td) { return new SourceInfo($"(({td.CSharpName}){Source})", Arg, MemberInfo, td.Type!, ILG); } [RequiresUnreferencedCode("calls InternalLoad")] public void LoadAddress(Type? elementType) { InternalLoad(elementType, asAddress: true); } [RequiresUnreferencedCode("calls InternalLoad")] public void Load(Type? elementType) { InternalLoad(elementType); } [RequiresUnreferencedCode("calls LoadMemberAddress")] private void InternalLoad(Type? elementType, bool asAddress = false) { Match match = s_regex.Match(Arg); if (match.Success) { object varA = ILG.GetVariable(match.Groups["a"].Value); Type varType = ILG.GetVariableType(varA); object varIA = ILG.GetVariable(match.Groups["ia"].Value); if (varType.IsArray) { ILG.Load(varA); ILG.Load(varIA); Type eType = varType.GetElementType()!; if (CodeGenerator.IsNullableGenericType(eType)) { ILG.Ldelema(eType); ConvertNullableValue(eType, elementType!); } else { if (eType.IsValueType) { ILG.Ldelema(eType); if (!asAddress) { ILG.Ldobj(eType); } } else ILG.Ldelem(eType); if (elementType != null) ILG.ConvertValue(eType, elementType); } } else { ILG.Load(varA); ILG.Load(varIA); MethodInfo get_Item = varType.GetMethod( "get_Item", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int) } )!; if (get_Item == null && typeof(IList).IsAssignableFrom(varType)) { get_Item = s_iListGetItemMethod.Value; } Debug.Assert(get_Item != null); ILG.Call(get_Item); Type eType = get_Item.ReturnType; if (CodeGenerator.IsNullableGenericType(eType)) { LocalBuilder localTmp = ILG.GetTempLocal(eType); ILG.Stloc(localTmp); ILG.Ldloca(localTmp); ConvertNullableValue(eType, elementType!); } else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType))) { throw new CodeGeneratorConversionException(eType, elementType, asAddress, "IsNotAssignableFrom"); } else { Convert(eType, elementType, asAddress); } } } else if (Source == "null") { ILG.Load(null); } else { object var; Type varType; if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null) { var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg); varType = ILG.GetVariableType(var); if (varType.IsValueType) ILG.LoadAddress(var); else ILG.Load(var); } else { var = ILG.GetVariable(Arg); varType = ILG.GetVariableType(var); if (CodeGenerator.IsNullableGenericType(varType) && varType.GetGenericArguments()[0] == elementType) { ILG.LoadAddress(var); ConvertNullableValue(varType, elementType); } else { if (asAddress) ILG.LoadAddress(var); else ILG.Load(var); } } if (MemberInfo != null) { Type memberType = (MemberInfo is FieldInfo) ? ((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType; if (CodeGenerator.IsNullableGenericType(memberType)) { ILG.LoadMemberAddress(MemberInfo); ConvertNullableValue(memberType, elementType!); } else { ILG.LoadMember(MemberInfo); Convert(memberType, elementType, asAddress); } } else { match = s_regex2.Match(Source); if (match.Success) { Debug.Assert(match.Groups["arg"].Value == Arg); Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type!)); if (asAddress) ILG.ConvertAddress(varType, Type!); else ILG.ConvertValue(varType, Type!); varType = Type!; } Convert(varType!, elementType, asAddress); } } } private void Convert(Type sourceType, Type? targetType, bool asAddress) { if (targetType != null) { if (asAddress) ILG.ConvertAddress(sourceType, targetType); else ILG.ConvertValue(sourceType, targetType); } } private void ConvertNullableValue( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type nullableType, Type targetType) { System.Diagnostics.Debug.Assert(targetType == nullableType || targetType.IsAssignableFrom(nullableType.GetGenericArguments()[0])); if (targetType != nullableType) { MethodInfo Nullable_get_Value = nullableType.GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ILG.Call(Nullable_get_Value); if (targetType != null) { ILG.ConvertValue(Nullable_get_Value.ReturnType, targetType); } } } public static implicit operator string(SourceInfo source) { return source.Source; } public static bool operator !=(SourceInfo? a, SourceInfo? b) { if (a is not null) return !a.Equals(b); return b is not null; } public static bool operator ==(SourceInfo? a, SourceInfo? b) { if (a is not null) return a.Equals(b); return b is null; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) return Source == null; SourceInfo? info = obj as SourceInfo; if (info != null) return Source == info.Source; return false; } public override int GetHashCode() { return (Source == null) ? 0 : Source.GetHashCode(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Xml.Extensions; namespace System.Xml.Serialization { internal sealed partial class SourceInfo { //a[ia] //((global::System.Xml.Serialization.XmlSerializerNamespaces)p[0]) [RegexGenerator("([(][(](?<t>[^)]+)[)])?(?<a>[^[]+)[[](?<ia>.+)[]][)]?")] private static partial Regex Regex1(); //((global::Microsoft.CFx.Test.Common.TypeLibrary.IXSType_9)o), @"IXSType_9", @"", true, true); [RegexGenerator("[(][(](?<cast>[^)]+)[)](?<arg>[^)]+)[)]")] private static partial Regex Regex2(); private static readonly Lazy<MethodInfo> s_iListGetItemMethod = new Lazy<MethodInfo>( () => { return typeof(IList).GetMethod( "get_Item", new Type[] { typeof(int) } )!; }); public string Source; public readonly string Arg; public readonly MemberInfo? MemberInfo; [DynamicallyAccessedMembers(TrimmerConstants.AllMethods)] public readonly Type? Type; public readonly CodeGenerator ILG; public SourceInfo(string source, string? arg, MemberInfo? memberInfo, [DynamicallyAccessedMembers(TrimmerConstants.AllMethods)] Type? type, CodeGenerator ilg) { this.Source = source; this.Arg = arg ?? source; this.MemberInfo = memberInfo; this.Type = type; this.ILG = ilg; } public SourceInfo CastTo(TypeDesc td) { return new SourceInfo($"(({td.CSharpName}){Source})", Arg, MemberInfo, td.Type!, ILG); } [RequiresUnreferencedCode("calls InternalLoad")] public void LoadAddress(Type? elementType) { InternalLoad(elementType, asAddress: true); } [RequiresUnreferencedCode("calls InternalLoad")] public void Load(Type? elementType) { InternalLoad(elementType); } [RequiresUnreferencedCode("calls LoadMemberAddress")] private void InternalLoad(Type? elementType, bool asAddress = false) { Match match = Regex1().Match(Arg); if (match.Success) { object varA = ILG.GetVariable(match.Groups["a"].Value); Type varType = ILG.GetVariableType(varA); object varIA = ILG.GetVariable(match.Groups["ia"].Value); if (varType.IsArray) { ILG.Load(varA); ILG.Load(varIA); Type eType = varType.GetElementType()!; if (CodeGenerator.IsNullableGenericType(eType)) { ILG.Ldelema(eType); ConvertNullableValue(eType, elementType!); } else { if (eType.IsValueType) { ILG.Ldelema(eType); if (!asAddress) { ILG.Ldobj(eType); } } else ILG.Ldelem(eType); if (elementType != null) ILG.ConvertValue(eType, elementType); } } else { ILG.Load(varA); ILG.Load(varIA); MethodInfo get_Item = varType.GetMethod( "get_Item", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int) } )!; if (get_Item == null && typeof(IList).IsAssignableFrom(varType)) { get_Item = s_iListGetItemMethod.Value; } Debug.Assert(get_Item != null); ILG.Call(get_Item); Type eType = get_Item.ReturnType; if (CodeGenerator.IsNullableGenericType(eType)) { LocalBuilder localTmp = ILG.GetTempLocal(eType); ILG.Stloc(localTmp); ILG.Ldloca(localTmp); ConvertNullableValue(eType, elementType!); } else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType))) { throw new CodeGeneratorConversionException(eType, elementType, asAddress, "IsNotAssignableFrom"); } else { Convert(eType, elementType, asAddress); } } } else if (Source == "null") { ILG.Load(null); } else { object var; Type varType; if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null) { var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg); varType = ILG.GetVariableType(var); if (varType.IsValueType) ILG.LoadAddress(var); else ILG.Load(var); } else { var = ILG.GetVariable(Arg); varType = ILG.GetVariableType(var); if (CodeGenerator.IsNullableGenericType(varType) && varType.GetGenericArguments()[0] == elementType) { ILG.LoadAddress(var); ConvertNullableValue(varType, elementType); } else { if (asAddress) ILG.LoadAddress(var); else ILG.Load(var); } } if (MemberInfo != null) { Type memberType = (MemberInfo is FieldInfo) ? ((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType; if (CodeGenerator.IsNullableGenericType(memberType)) { ILG.LoadMemberAddress(MemberInfo); ConvertNullableValue(memberType, elementType!); } else { ILG.LoadMember(MemberInfo); Convert(memberType, elementType, asAddress); } } else { match = Regex2().Match(Source); if (match.Success) { Debug.Assert(match.Groups["arg"].Value == Arg); Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type!)); if (asAddress) ILG.ConvertAddress(varType, Type!); else ILG.ConvertValue(varType, Type!); varType = Type!; } Convert(varType!, elementType, asAddress); } } } private void Convert(Type sourceType, Type? targetType, bool asAddress) { if (targetType != null) { if (asAddress) ILG.ConvertAddress(sourceType, targetType); else ILG.ConvertValue(sourceType, targetType); } } private void ConvertNullableValue( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type nullableType, Type targetType) { System.Diagnostics.Debug.Assert(targetType == nullableType || targetType.IsAssignableFrom(nullableType.GetGenericArguments()[0])); if (targetType != nullableType) { MethodInfo Nullable_get_Value = nullableType.GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ILG.Call(Nullable_get_Value); if (targetType != null) { ILG.ConvertValue(Nullable_get_Value.ReturnType, targetType); } } } public static implicit operator string(SourceInfo source) { return source.Source; } public static bool operator !=(SourceInfo? a, SourceInfo? b) { if (a is not null) return !a.Equals(b); return b is not null; } public static bool operator ==(SourceInfo? a, SourceInfo? b) { if (a is not null) return a.Equals(b); return b is null; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) return Source == null; SourceInfo? info = obj as SourceInfo; if (info != null) return Source == info.Source; return false; } public override int GetHashCode() { return (Source == null) ? 0 : Source.GetHashCode(); } } }
1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.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.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Xml.Extensions; internal class XmlSerializationILGen { private int _nextMethodNumber; private readonly Dictionary<TypeMapping, string> _methodNames = new Dictionary<TypeMapping, string>(); // Lookup name->created Method private readonly Dictionary<string, MethodBuilderInfo> _methodBuilders = new Dictionary<string, MethodBuilderInfo>(); // Lookup name->created Type internal Dictionary<string, Type> CreatedTypes = new Dictionary<string, Type>(); // Lookup name->class Member internal Dictionary<string, MemberInfo> memberInfos = new Dictionary<string, MemberInfo>(); private readonly ReflectionAwareILGen _raCodeGen; private readonly TypeScope[] _scopes; private readonly TypeDesc? _stringTypeDesc; private readonly TypeDesc? _qnameTypeDesc; private readonly string _className; private TypeMapping[]? _referencedMethods; private int _references; private readonly HashSet<TypeMapping> _generatedMethods = new HashSet<TypeMapping>(); private ModuleBuilder? _moduleBuilder; private readonly TypeAttributes _typeAttributes; protected TypeBuilder typeBuilder = null!; protected CodeGenerator ilg = null!; [RequiresUnreferencedCode("Calls GetTypeDesc")] internal XmlSerializationILGen(TypeScope[] scopes, string access, string className) { _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareILGen(); _className = className; System.Diagnostics.Debug.Assert(access == "public"); _typeAttributes = TypeAttributes.Public; } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Dictionary<TypeMapping, string> MethodNames { get { return _methodNames; } } internal HashSet<TypeMapping> GeneratedMethods { get { return _generatedMethods; } } internal ModuleBuilder ModuleBuilder { get { System.Diagnostics.Debug.Assert(_moduleBuilder != null); return _moduleBuilder; } set { System.Diagnostics.Debug.Assert(_moduleBuilder == null && value != null); _moduleBuilder = value; } } internal TypeAttributes TypeAttributes { get { return _typeAttributes; } } private static readonly Dictionary<string, Regex> s_regexs = new Dictionary<string, Regex>(); internal static Regex NewRegex(string pattern) { Regex? regex; lock (s_regexs) { if (!s_regexs.TryGetValue(pattern, out regex)) { regex = new Regex(pattern); s_regexs.Add(pattern, regex); } } return regex; } internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName, MethodAttributes attributes, Type? returnType, Type[] parameterTypes) { MethodBuilderInfo? methodBuilderInfo; if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo)) { MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodName, attributes, returnType, parameterTypes); methodBuilderInfo = new MethodBuilderInfo(methodBuilder, parameterTypes); _methodBuilders.Add(methodName, methodBuilderInfo); } #if DEBUG else { methodBuilderInfo.Validate(returnType, parameterTypes, attributes); } #endif return methodBuilderInfo.MethodBuilder; } internal MethodBuilderInfo GetMethodBuilder(string methodName) { System.Diagnostics.Debug.Assert(_methodBuilders.ContainsKey(methodName)); return _methodBuilders[methodName]; } [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 (!_generatedMethods.Contains(mapping)) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } string? methodName; _methodNames.TryGetValue(mapping, out methodName); return methodName; } 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; } [return: NotNullIfNotNull("value")] internal string? GetCSharpString(string? value) { return ReflectionAwareILGen.GetCSharpString(value); } [RequiresUnreferencedCode("calls LoadMember")] internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publicName, TypeBuilder serializerContractTypeBuilder) { FieldBuilder fieldBuilder = serializerContractTypeBuilder.DefineField( privateName, typeof(Hashtable), FieldAttributes.Private ); ilg = new CodeGenerator(serializerContractTypeBuilder); PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty( publicName, PropertyAttributes.None, CallingConventions.HasThis, typeof(Hashtable), null, null, null, null, null); ilg.BeginMethod( typeof(Hashtable), $"get_{publicName}", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); // this 'if' ends in GenerateHashtableGetEnd ilg.If(Cmp.EqualTo); ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp"); ilg.New(Hashtable_ctor); ilg.Stloc(_tmpLoc); return fieldBuilder; } [RequiresUnreferencedCode("calls LoadMember")] internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder) { ilg!.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); ilg.If(Cmp.EqualTo); { ilg.Ldarg(0); ilg.Ldloc(typeof(Hashtable), "_tmp"); ilg.StoreMember(fieldBuilder); } ilg.EndIf(); // 'endif' from GenerateHashtableGetBegin ilg.EndIf(); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.GotoMethodEnd(); ilg.EndMethod(); } [RequiresUnreferencedCode("calls GenerateHashtableGetBegin")] internal FieldBuilder GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder) { FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, publicName, serializerContractTypeBuilder); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod( "set_Item", new Type[] { typeof(object), typeof(object) } )!; for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(xmlMappings[i].Key)); ilg.Ldstr(GetCSharpString(methods[i])); ilg.Call(Hashtable_set_Item); } } GenerateHashtableGetEnd(fieldBuilder); return fieldBuilder; } internal void GenerateSupportedTypes(Type[] types, TypeBuilder serializerContractTypeBuilder) { ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(bool), "CanSerialize", new Type[] { typeof(Type) }, new string[] { "type" }, CodeGenerator.PublicOverrideMethodAttributes); var uniqueTypes = new HashSet<Type>(); for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (!uniqueTypes.Add(type)) continue; // DDB172141: Wrong generated CS for serializer of List<string> type if (type.IsGenericType || type.ContainsGenericParameters) continue; ilg.Ldarg("type"); ilg.Ldc(type); ilg.If(Cmp.EqualTo); { ilg.Ldc(true); ilg.GotoMethodEnd(); } ilg.EndIf(); } ilg.Ldc(false); ilg.GotoMethodEnd(); ilg.EndMethod(); } [RequiresUnreferencedCode("Uses CreatedTypes Dictionary")] internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder!, CodeIdentifier.GetCSharpName(baseSerializer), TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit, typeof(XmlSerializer), Type.EmptyTypes); ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg = new CodeGenerator(baseSerializerTypeBuilder); ilg.BeginMethod(typeof(XmlSerializationReader), "CreateReader", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(readerCtor); ilg.EndMethod(); ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.BeginMethod(typeof(XmlSerializationWriter), "CreateWriter", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(writerCtor); ilg.EndMethod(); baseSerializerTypeBuilder.DefineDefaultConstructor( MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(baseSerializerType.Name, baseSerializerType); return baseSerializer; } [RequiresUnreferencedCode("uses CreatedTypes dictionary")] 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); TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder!, CodeIdentifier.GetCSharpName(serializerName), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, CreatedTypes[baseSerializer], Type.EmptyTypes ); ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(bool), "CanDeserialize", new Type[] { typeof(XmlReader) }, new string[] { "xmlReader" }, CodeGenerator.PublicOverrideMethodAttributes ); if (mapping.Accessor.Any) { ilg.Ldc(true); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } else { MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod( "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Ldarg(ilg.GetArg("xmlReader")); ilg.Ldstr(GetCSharpString(mapping.Accessor.Name)); ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace)); ilg.Call(XmlReader_IsStartElement); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); if (writeMethod != null) { ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(void), "Serialize", new Type[] { typeof(object), typeof(XmlSerializationWriter) }, new string[] { "objectToSerialize", "writer" }, CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod( writeMethod, CodeGenerator.InstanceBindingFlags, new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) } )!; ilg.Ldarg("writer"); ilg.Castclass(CreatedTypes[writerClass]); ilg.Ldarg("objectToSerialize"); if (mapping is XmlMembersMapping) { ilg.ConvertValue(typeof(object), typeof(object[])); } ilg.Call(writerType_writeMethod); ilg.EndMethod(); } if (readMethod != null) { ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(object), "Deserialize", new Type[] { typeof(XmlSerializationReader) }, new string[] { "reader" }, CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod( readMethod, CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg("reader"); ilg.Castclass(CreatedTypes[readerClass]); ilg.Call(readerType_readMethod); ilg.EndMethod(); } typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes); Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(typedSerializerType.Name, typedSerializerType); return typedSerializerType.Name; } [RequiresUnreferencedCode("calls GetConstructor")] private FieldBuilder GenerateTypedSerializers(Dictionary<string, string> serializers, TypeBuilder serializerContractTypeBuilder) { string privateName = "typedSerializers"; FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, "TypedSerializers", serializerContractTypeBuilder); MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } )!; foreach (string key in serializers.Keys) { ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(key)); ilg.New(ctor); ilg.Call(Hashtable_Add); } GenerateHashtableGetEnd(fieldBuilder); return fieldBuilder; } //GenerateGetSerializer(serializers, xmlMappings); [RequiresUnreferencedCode("Uses CreatedTypes Dictionary")] private void GenerateGetSerializer(Dictionary<string, string> serializers, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder) { ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(XmlSerializer), "GetSerializer", new Type[] { typeof(Type) }, new string[] { "type" }, CodeGenerator.PublicOverrideMethodAttributes); 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; // DDB172141: Wrong generated CS for serializer of List<string> type if (type.IsGenericType || type.ContainsGenericParameters) continue; ilg.Ldarg("type"); ilg.Ldc(type); ilg.If(Cmp.EqualTo); { ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key!]].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); } } ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls GenerateTypedSerializers")] internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary<string, string> serializers) { TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder!, "XmlSerializerContract", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(XmlSerializerImplementation), Type.EmptyTypes ); ilg = new CodeGenerator(serializerContractTypeBuilder); PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty( "Reader", PropertyAttributes.None, typeof(XmlSerializationReader), null, null, null, null, null); ilg.BeginMethod( typeof(XmlSerializationReader), "get_Reader", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); ilg.EndMethod(); ilg = new CodeGenerator(serializerContractTypeBuilder); propertyBuilder = serializerContractTypeBuilder.DefineProperty( "Writer", PropertyAttributes.None, typeof(XmlSerializationWriter), null, null, null, null, null); ilg.BeginMethod( typeof(XmlSerializationWriter), "get_Writer", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ctor = CreatedTypes[writerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); ilg.EndMethod(); FieldBuilder readMethodsField = GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings, serializerContractTypeBuilder); FieldBuilder writeMethodsField = GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings, serializerContractTypeBuilder); FieldBuilder typedSerializersField = GenerateTypedSerializers(serializers, serializerContractTypeBuilder); GenerateSupportedTypes(types, serializerContractTypeBuilder); GenerateGetSerializer(serializers, xmlMappings, serializerContractTypeBuilder); // Default ctor ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(void), ".ctor", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicMethodAttributes | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName ); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(readMethodsField); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(writeMethodsField); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(typedSerializersField); ilg.Ldarg(0); ilg.Call(baseCtor); ilg.EndMethod(); // Instantiate type Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(serializerContractType.Name, serializerContractType); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc!.CanBeElementValue; } [RequiresUnreferencedCode("calls ILGenLoad")] internal void ILGenLoad(string source) { ILGenLoad(source, null); } [RequiresUnreferencedCode("calls LoadMember")] internal void ILGenLoad(string source, Type? type) { if (source.StartsWith("o.@", StringComparison.Ordinal)) { System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); MemberInfo memInfo = memberInfos[source.Substring(3)]; ilg!.LoadMember(ilg.GetVariable("o"), memInfo); if (type != null) { Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType; ilg.ConvertValue(memType, type); } } else { SourceInfo info = new SourceInfo(source, null, null, null, ilg!); info.Load(type); } } } }
// 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.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Xml.Extensions; internal class XmlSerializationILGen { private int _nextMethodNumber; private readonly Dictionary<TypeMapping, string> _methodNames = new Dictionary<TypeMapping, string>(); // Lookup name->created Method private readonly Dictionary<string, MethodBuilderInfo> _methodBuilders = new Dictionary<string, MethodBuilderInfo>(); // Lookup name->created Type internal Dictionary<string, Type> CreatedTypes = new Dictionary<string, Type>(); // Lookup name->class Member internal Dictionary<string, MemberInfo> memberInfos = new Dictionary<string, MemberInfo>(); private readonly ReflectionAwareILGen _raCodeGen; private readonly TypeScope[] _scopes; private readonly TypeDesc? _stringTypeDesc; private readonly TypeDesc? _qnameTypeDesc; private readonly string _className; private TypeMapping[]? _referencedMethods; private int _references; private readonly HashSet<TypeMapping> _generatedMethods = new HashSet<TypeMapping>(); private ModuleBuilder? _moduleBuilder; private readonly TypeAttributes _typeAttributes; protected TypeBuilder typeBuilder = null!; protected CodeGenerator ilg = null!; [RequiresUnreferencedCode("Calls GetTypeDesc")] internal XmlSerializationILGen(TypeScope[] scopes, string access, string className) { _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareILGen(); _className = className; System.Diagnostics.Debug.Assert(access == "public"); _typeAttributes = TypeAttributes.Public; } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Dictionary<TypeMapping, string> MethodNames { get { return _methodNames; } } internal HashSet<TypeMapping> GeneratedMethods { get { return _generatedMethods; } } internal ModuleBuilder ModuleBuilder { get { System.Diagnostics.Debug.Assert(_moduleBuilder != null); return _moduleBuilder; } set { System.Diagnostics.Debug.Assert(_moduleBuilder == null && value != null); _moduleBuilder = value; } } internal TypeAttributes TypeAttributes { get { return _typeAttributes; } } internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName, MethodAttributes attributes, Type? returnType, Type[] parameterTypes) { MethodBuilderInfo? methodBuilderInfo; if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo)) { MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodName, attributes, returnType, parameterTypes); methodBuilderInfo = new MethodBuilderInfo(methodBuilder, parameterTypes); _methodBuilders.Add(methodName, methodBuilderInfo); } #if DEBUG else { methodBuilderInfo.Validate(returnType, parameterTypes, attributes); } #endif return methodBuilderInfo.MethodBuilder; } internal MethodBuilderInfo GetMethodBuilder(string methodName) { System.Diagnostics.Debug.Assert(_methodBuilders.ContainsKey(methodName)); return _methodBuilders[methodName]; } [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 (!_generatedMethods.Contains(mapping)) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } string? methodName; _methodNames.TryGetValue(mapping, out methodName); return methodName; } 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; } [return: NotNullIfNotNull("value")] internal string? GetCSharpString(string? value) { return ReflectionAwareILGen.GetCSharpString(value); } [RequiresUnreferencedCode("calls LoadMember")] internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publicName, TypeBuilder serializerContractTypeBuilder) { FieldBuilder fieldBuilder = serializerContractTypeBuilder.DefineField( privateName, typeof(Hashtable), FieldAttributes.Private ); ilg = new CodeGenerator(serializerContractTypeBuilder); PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty( publicName, PropertyAttributes.None, CallingConventions.HasThis, typeof(Hashtable), null, null, null, null, null); ilg.BeginMethod( typeof(Hashtable), $"get_{publicName}", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); // this 'if' ends in GenerateHashtableGetEnd ilg.If(Cmp.EqualTo); ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp"); ilg.New(Hashtable_ctor); ilg.Stloc(_tmpLoc); return fieldBuilder; } [RequiresUnreferencedCode("calls LoadMember")] internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder) { ilg!.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); ilg.If(Cmp.EqualTo); { ilg.Ldarg(0); ilg.Ldloc(typeof(Hashtable), "_tmp"); ilg.StoreMember(fieldBuilder); } ilg.EndIf(); // 'endif' from GenerateHashtableGetBegin ilg.EndIf(); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.GotoMethodEnd(); ilg.EndMethod(); } [RequiresUnreferencedCode("calls GenerateHashtableGetBegin")] internal FieldBuilder GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder) { FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, publicName, serializerContractTypeBuilder); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod( "set_Item", new Type[] { typeof(object), typeof(object) } )!; for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(xmlMappings[i].Key)); ilg.Ldstr(GetCSharpString(methods[i])); ilg.Call(Hashtable_set_Item); } } GenerateHashtableGetEnd(fieldBuilder); return fieldBuilder; } internal void GenerateSupportedTypes(Type[] types, TypeBuilder serializerContractTypeBuilder) { ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(bool), "CanSerialize", new Type[] { typeof(Type) }, new string[] { "type" }, CodeGenerator.PublicOverrideMethodAttributes); var uniqueTypes = new HashSet<Type>(); for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (!uniqueTypes.Add(type)) continue; // DDB172141: Wrong generated CS for serializer of List<string> type if (type.IsGenericType || type.ContainsGenericParameters) continue; ilg.Ldarg("type"); ilg.Ldc(type); ilg.If(Cmp.EqualTo); { ilg.Ldc(true); ilg.GotoMethodEnd(); } ilg.EndIf(); } ilg.Ldc(false); ilg.GotoMethodEnd(); ilg.EndMethod(); } [RequiresUnreferencedCode("Uses CreatedTypes Dictionary")] internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder!, CodeIdentifier.GetCSharpName(baseSerializer), TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit, typeof(XmlSerializer), Type.EmptyTypes); ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg = new CodeGenerator(baseSerializerTypeBuilder); ilg.BeginMethod(typeof(XmlSerializationReader), "CreateReader", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(readerCtor); ilg.EndMethod(); ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.BeginMethod(typeof(XmlSerializationWriter), "CreateWriter", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(writerCtor); ilg.EndMethod(); baseSerializerTypeBuilder.DefineDefaultConstructor( MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(baseSerializerType.Name, baseSerializerType); return baseSerializer; } [RequiresUnreferencedCode("uses CreatedTypes dictionary")] 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); TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder!, CodeIdentifier.GetCSharpName(serializerName), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, CreatedTypes[baseSerializer], Type.EmptyTypes ); ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(bool), "CanDeserialize", new Type[] { typeof(XmlReader) }, new string[] { "xmlReader" }, CodeGenerator.PublicOverrideMethodAttributes ); if (mapping.Accessor.Any) { ilg.Ldc(true); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } else { MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod( "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Ldarg(ilg.GetArg("xmlReader")); ilg.Ldstr(GetCSharpString(mapping.Accessor.Name)); ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace)); ilg.Call(XmlReader_IsStartElement); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); if (writeMethod != null) { ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(void), "Serialize", new Type[] { typeof(object), typeof(XmlSerializationWriter) }, new string[] { "objectToSerialize", "writer" }, CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod( writeMethod, CodeGenerator.InstanceBindingFlags, new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) } )!; ilg.Ldarg("writer"); ilg.Castclass(CreatedTypes[writerClass]); ilg.Ldarg("objectToSerialize"); if (mapping is XmlMembersMapping) { ilg.ConvertValue(typeof(object), typeof(object[])); } ilg.Call(writerType_writeMethod); ilg.EndMethod(); } if (readMethod != null) { ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(object), "Deserialize", new Type[] { typeof(XmlSerializationReader) }, new string[] { "reader" }, CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod( readMethod, CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg("reader"); ilg.Castclass(CreatedTypes[readerClass]); ilg.Call(readerType_readMethod); ilg.EndMethod(); } typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes); Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(typedSerializerType.Name, typedSerializerType); return typedSerializerType.Name; } [RequiresUnreferencedCode("calls GetConstructor")] private FieldBuilder GenerateTypedSerializers(Dictionary<string, string> serializers, TypeBuilder serializerContractTypeBuilder) { string privateName = "typedSerializers"; FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, "TypedSerializers", serializerContractTypeBuilder); MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } )!; foreach (string key in serializers.Keys) { ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(key)); ilg.New(ctor); ilg.Call(Hashtable_Add); } GenerateHashtableGetEnd(fieldBuilder); return fieldBuilder; } //GenerateGetSerializer(serializers, xmlMappings); [RequiresUnreferencedCode("Uses CreatedTypes Dictionary")] private void GenerateGetSerializer(Dictionary<string, string> serializers, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder) { ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(XmlSerializer), "GetSerializer", new Type[] { typeof(Type) }, new string[] { "type" }, CodeGenerator.PublicOverrideMethodAttributes); 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; // DDB172141: Wrong generated CS for serializer of List<string> type if (type.IsGenericType || type.ContainsGenericParameters) continue; ilg.Ldarg("type"); ilg.Ldc(type); ilg.If(Cmp.EqualTo); { ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key!]].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); } } ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls GenerateTypedSerializers")] internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary<string, string> serializers) { TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder!, "XmlSerializerContract", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(XmlSerializerImplementation), Type.EmptyTypes ); ilg = new CodeGenerator(serializerContractTypeBuilder); PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty( "Reader", PropertyAttributes.None, typeof(XmlSerializationReader), null, null, null, null, null); ilg.BeginMethod( typeof(XmlSerializationReader), "get_Reader", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); ilg.EndMethod(); ilg = new CodeGenerator(serializerContractTypeBuilder); propertyBuilder = serializerContractTypeBuilder.DefineProperty( "Writer", PropertyAttributes.None, typeof(XmlSerializationWriter), null, null, null, null, null); ilg.BeginMethod( typeof(XmlSerializationWriter), "get_Writer", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ctor = CreatedTypes[writerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); ilg.EndMethod(); FieldBuilder readMethodsField = GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings, serializerContractTypeBuilder); FieldBuilder writeMethodsField = GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings, serializerContractTypeBuilder); FieldBuilder typedSerializersField = GenerateTypedSerializers(serializers, serializerContractTypeBuilder); GenerateSupportedTypes(types, serializerContractTypeBuilder); GenerateGetSerializer(serializers, xmlMappings, serializerContractTypeBuilder); // Default ctor ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(void), ".ctor", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicMethodAttributes | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName ); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(readMethodsField); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(writeMethodsField); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(typedSerializersField); ilg.Ldarg(0); ilg.Call(baseCtor); ilg.EndMethod(); // Instantiate type Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(serializerContractType.Name, serializerContractType); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc!.CanBeElementValue; } [RequiresUnreferencedCode("calls ILGenLoad")] internal void ILGenLoad(string source) { ILGenLoad(source, null); } [RequiresUnreferencedCode("calls LoadMember")] internal void ILGenLoad(string source, Type? type) { if (source.StartsWith("o.@", StringComparison.Ordinal)) { System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); MemberInfo memInfo = memberInfos[source.Substring(3)]; ilg!.LoadMember(ilg.GetVariable("o"), memInfo); if (type != null) { Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType; ilg.ConvertValue(memType, type); } } else { SourceInfo info = new SourceInfo(source, null, null, null, ilg!); info.Load(type); } } } }
1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Security; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Schema; using System.Xml.Extensions; using System.Diagnostics.CodeAnalysis; internal sealed class XmlSerializationReaderILGen : XmlSerializationILGen { private readonly Dictionary<string, string> _idNames = new Dictionary<string, string>(); // Mapping name->id_XXXNN field private readonly Dictionary<string, FieldBuilder> _idNameFields = new Dictionary<string, FieldBuilder>(); private Dictionary<string, EnumMapping>? _enums; private int _nextIdNumber; internal Dictionary<string, EnumMapping> Enums { get { if (_enums == null) { _enums = new Dictionary<string, EnumMapping>(); } return _enums; } } private sealed class Member { private readonly string _source; private readonly string _arrayName; private readonly string _arraySource; private readonly string _choiceArrayName; private readonly string? _choiceSource; private readonly string? _choiceArraySource; private readonly MemberMapping _mapping; private readonly bool _isArray; private readonly bool _isList; private bool _isNullable; private int _fixupIndex = -1; private string? _paramsReadSource; private string? _checkSpecifiedSource; internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, null, arrayName, i, mapping, false, null) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, null, arrayName, i, mapping, false, choiceSource) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, arraySource, arrayName, i, mapping, false, null) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, arraySource, arrayName, i, mapping, false, choiceSource) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) : this(outerClass, source, null, arrayName, i, mapping, multiRef, null) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) { _source = source; _arrayName = string.Create(CultureInfo.InvariantCulture, $"{arrayName}_{i}"); _choiceArrayName = $"choice_{_arrayName}"; _choiceSource = choiceSource; if (mapping.TypeDesc!.IsArrayLike) { if (arraySource != null) _arraySource = arraySource; else _arraySource = outerClass.GetArraySource(mapping.TypeDesc, _arrayName, multiRef); _isArray = mapping.TypeDesc.IsArray; _isList = !_isArray; if (mapping.ChoiceIdentifier != null) { _choiceArraySource = outerClass.GetArraySource(mapping.TypeDesc, _choiceArrayName, multiRef); string a = _choiceArrayName; string c = $"c{a}"; string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName; string castString = $"({choiceTypeFullName}[])"; string init = $"{a} = {castString}EnsureArrayIndex({a}, {c}, {outerClass.RaCodeGen.GetStringForTypeof(choiceTypeFullName)});"; _choiceArraySource = init + outerClass.RaCodeGen.GetStringForArrayMember(a, $"{c}++", mapping.ChoiceIdentifier.Mapping.TypeDesc); } else { _choiceArraySource = _choiceSource; } } else { _arraySource = arraySource == null ? source : arraySource; _choiceArraySource = _choiceSource; } _mapping = mapping; } internal MemberMapping Mapping { get { return _mapping; } } internal string Source { get { return _source; } } internal string ArrayName { get { return _arrayName; } } internal string ArraySource { get { return _arraySource; } } internal bool IsList { get { return _isList; } } internal bool IsArrayLike { get { return (_isArray || _isList); } } internal bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } internal int FixupIndex { get { return _fixupIndex; } set { _fixupIndex = value; } } internal string? ParamsReadSource { get { return _paramsReadSource; } set { _paramsReadSource = value; } } internal string? CheckSpecifiedSource { get { return _checkSpecifiedSource; } set { _checkSpecifiedSource = value; } } internal string? ChoiceSource { get { return _choiceSource; } } internal string ChoiceArrayName { get { return _choiceArrayName; } } internal string? ChoiceArraySource { get { return _choiceArraySource; } } } [RequiresUnreferencedCode("Creates XmlSerializationILGen")] internal XmlSerializationReaderILGen(TypeScope[] scopes, string access, string className) : base(scopes, access, className) { } [RequiresUnreferencedCode("calls WriteReflectionInit")] internal void GenerateBegin() { this.typeBuilder = CodeGenerator.CreateTypeBuilder( ModuleBuilder, ClassName, TypeAttributes | TypeAttributes.BeforeFieldInit, typeof(XmlSerializationReader), Type.EmptyTypes); foreach (TypeScope scope in Scopes) { foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping is StructMapping || mapping is EnumMapping || mapping is NullableMapping) MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } RaCodeGen.WriteReflectionInit(scope); } } [RequiresUnreferencedCode("calls WriteStructMethod")] internal override void GenerateMethod(TypeMapping mapping) { if (!GeneratedMethods.Add(mapping)) return; if (mapping is StructMapping) { WriteStructMethod((StructMapping)mapping); } else if (mapping is EnumMapping) { WriteEnumMethod((EnumMapping)mapping); } else if (mapping is NullableMapping) { WriteNullableMethod((NullableMapping)mapping); } } [RequiresUnreferencedCode("calls GenerateReferencedMethods")] internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] types) { GenerateReferencedMethods(); GenerateInitCallbacksMethod(); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod(typeof(void), "InitIDs", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NameTable = typeof(XmlReader).GetMethod( "get_NameTable", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlNameTable_Add = typeof(XmlNameTable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; foreach (string id in _idNames.Keys) { ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NameTable); ilg.Ldstr(GetCSharpString(id)); ilg.Call(XmlNameTable_Add); Debug.Assert(_idNameFields.ContainsKey(id)); ilg.StoreMember(_idNameFields[id]); } ilg.EndMethod(); this.typeBuilder.DefineDefaultConstructor( CodeGenerator.PublicMethodAttributes); Type readerType = this.typeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(readerType.Name, readerType); } [RequiresUnreferencedCode("calls GenerateMembersElement")] internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsReadable) return null; if (!xmlMapping.GenerateSerializer) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); if (xmlMapping is XmlTypeMapping) return GenerateTypeElement((XmlTypeMapping)xmlMapping); else if (xmlMapping is XmlMembersMapping) return GenerateMembersElement((XmlMembersMapping)xmlMapping); else throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } [RequiresUnreferencedCode("calls LoadMember")] private void WriteIsStartTag(string? name, string? ns) { WriteID(name); WriteID(ns); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod( "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[name ?? string.Empty]); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[ns ?? string.Empty]); ilg.Call(XmlReader_IsStartElement); ilg.If(); } [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WriteUnknownNode(string func, string node, ElementAccessor? e, bool anyIfs) { if (anyIfs) { ilg.Else(); } List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); Debug.Assert(node == "null" || node == "(object)p"); if (node == "null") ilg.Load(null); else { object pVar = ilg.GetVariable("p"); ilg.Load(pVar); ilg.ConvertValue(ilg.GetVariableType(pVar), typeof(object)); } argTypes.Add(typeof(object)); if (e != null) { string? expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; expectedElement += ":"; expectedElement += e.Name; ilg.Ldstr(ReflectionAwareILGen.GetCSharpString(expectedElement)); argTypes.Add(typeof(string)); } MethodInfo method = typeof(XmlSerializationReader).GetMethod( func, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() )!; ilg.Call(method); if (anyIfs) { ilg.EndIf(); } } private void GenerateInitCallbacksMethod() { ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod(typeof(void), "InitCallbacks", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.EndMethod(); } [RequiresUnreferencedCode("calls GenerateLiteralMembersElement")] private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { return GenerateLiteralMembersElement(xmlMembersMapping); } private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { string? choiceSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mappings.Length; j++) { if (mappings[j].Name == member.ChoiceIdentifier.MemberName) { choiceSource = $"p[{j}]"; break; } } #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping.")); #endif } return choiceSource!; } private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) { if (mapping.ChoiceIdentifier == null) return ""; CodeIdentifier.CheckValidIdentifier(mapping.ChoiceIdentifier.MemberName); return RaCodeGen.GetStringForMember(parent, mapping.ChoiceIdentifier.MemberName, parentTypeDesc); } [RequiresUnreferencedCode("calls InitializeValueTypes")] private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(object[]), methodName, Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicMethodAttributes ); ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); LocalBuilder localP = ilg.DeclareLocal(typeof(object[]), "p"); ilg.NewArray(typeof(object), mappings.Length); ilg.Stloc(localP); InitializeValueTypes("p", mappings); if (hasWrapperElement) { WriteWhileNotLoopStart(); WriteIsStartTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""); } Member? anyText = null; Member? anyElement = null; Member? anyAttribute = null; var membersList = new List<Member>(); var textOrArrayMembersList = new List<Member>(); var attributeMembersList = new List<Member>(); for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; string source = $"p[{i}]"; string arraySource = source; if (mapping.Xmlns != null) { arraySource = $"(({mapping.TypeDesc!.CSharpName}){source})"; } string choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); Member anyMember = new Member(this, source, null, "a", i, mapping, choiceSource); if (!mapping.IsSequence) member.ParamsReadSource = $"paramsRead[{i}]"; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) { string nameSpecified = $"{mapping.Name}Specified"; for (int j = 0; j < mappings.Length; j++) { if (mappings[j].Name == nameSpecified) { member.CheckSpecifiedSource = $"p[{j}]"; break; } } } bool foundAnyElement = false; if (mapping.Text != null) anyText = anyMember; if (mapping.Attribute != null && mapping.Attribute.Any) anyAttribute = anyMember; if (mapping.Attribute != null || mapping.Xmlns != null) attributeMembersList.Add(member); else if (mapping.Text != null) textOrArrayMembersList.Add(member); if (!mapping.IsSequence) { for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { anyElement = anyMember; if (mapping.Attribute == null && mapping.Text == null) textOrArrayMembersList.Add(anyMember); foundAnyElement = true; break; } } } if (mapping.Attribute != null || mapping.Text != null || foundAnyElement) membersList.Add(anyMember); else if (mapping.TypeDesc!.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { membersList.Add(anyMember); textOrArrayMembersList.Add(anyMember); } else { if (mapping.TypeDesc.IsArrayLike && !mapping.TypeDesc.IsArray) member.ParamsReadSource = null; // collection membersList.Add(member); } } Member[] members = membersList.ToArray(); Member[] textOrArrayMembers = textOrArrayMembersList.ToArray(); if (members.Length > 0 && members[0].Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(true); ilg.Call(XmlSerializationReader_set_IsReturnValue); } WriteParamsRead(mappings.Length); if (attributeMembersList.Count > 0) { Member[] attributeMembers = attributeMembersList.ToArray(); WriteMemberBegin(attributeMembers); WriteAttributes(attributeMembers, anyAttribute, "UnknownNode", localP); WriteMemberEnd(attributeMembers); MethodInfo XmlReader_MoveToElement = typeof(XmlReader).GetMethod( "MoveToElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); ilg.Pop(); } WriteMemberBegin(textOrArrayMembers); if (hasWrapperElement) { MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); { MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); ilg.WhileContinue(); } ilg.EndIf(); MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); } if (IsSequence(members)) { ilg.Ldc(0); ilg.Stloc(typeof(int), "state"); } WriteWhileNotLoopStart(); string unknownNode = $"UnknownNode((object)p, {ExpectedElements(members)});"; WriteMemberElements(members, unknownNode, unknownNode, anyElement, anyText); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); WriteMemberEnd(textOrArrayMembers); if (hasWrapperElement) { MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); WriteUnknownNode("UnknownNode", "null", element, true); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); } ilg.Ldloc(ilg.GetLocal("p")); ilg.EndMethod(); return methodName; } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { if (!mappings[i].TypeDesc!.IsValueType) continue; LocalBuilder arrayLoc = ilg.GetLocal(arrayName); ilg.Ldloc(arrayLoc); ilg.Ldc(i); RaCodeGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc!.Type!, false, false); ilg.ConvertValue(mappings[i].TypeDesc!.Type!, typeof(object)); ilg.Stelem(arrayLoc.LocalType.GetElementType()!); } } [RequiresUnreferencedCode("calls WriteMemberElements")] private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(object), methodName, Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicMethodAttributes ); LocalBuilder oLoc = ilg.DeclareLocal(typeof(object), "o"); ilg.Load(null); ilg.Stloc(oLoc); MemberMapping member = new MemberMapping(); member.TypeDesc = mapping.TypeDesc; //member.ReadOnly = !mapping.TypeDesc.HasDefaultConstructor; member.Elements = new ElementAccessor[] { element }; Member[] members = new Member[] { new Member(this, "o", "o", "a", 0, member) }; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); string unknownNode = $"UnknownNode(null, {ExpectedElements(members)});"; WriteMemberElements(members, "throw CreateUnknownNodeException();", unknownNode, element.Any ? members[0] : null, null); ilg.Ldloc(oLoc); // for code compat as compiler does ilg.Stloc(ilg.ReturnLocal); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); return methodName; } private string NextMethodName(string name) => string.Create(CultureInfo.InvariantCulture, $"Read{++NextMethodNumber}_{CodeIdentifier.MakeValidInternal(name)}"); private string NextIdName(string name) => string.Create(CultureInfo.InvariantCulture, $"id{++_nextIdNumber}_{CodeIdentifier.MakeValidInternal(name)}"); [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WritePrimitive(TypeMapping mapping, string source) { System.Diagnostics.Debug.Assert(source == "Reader.ReadElementString()" || source == "Reader.ReadString()" || source == "false" || source == "Reader.Value" || source == "vals[i]"); if (mapping is EnumMapping) { string? enumMethodName = ReferenceMapping(mapping); if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc!.Name)); // For enum, its read method (eg. Read1_Gender) could be called multiple times // prior to its declaration. MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, enumMethodName, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); ilg.Ldarg(0); if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); } else if (source == "Reader.Value") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); } else if (source == "vals[i]") { LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); } else if (source == "false") { ilg.Ldc(false); } else { throw Globals.NotSupported($"Unexpected: {source}"); } ilg.Call(methodBuilder); } else if (mapping.TypeDesc == StringTypeDesc) { if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); } else if (source == "Reader.Value") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); } else if (source == "vals[i]") { LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); } else { throw Globals.NotSupported($"Unexpected: {source}"); } } else if (mapping.TypeDesc!.FormatterName == "String") { System.Diagnostics.Debug.Assert(source == "Reader.Value" || source == "Reader.ReadElementString()" || source == "vals[i]"); if (source == "vals[i]") { if (mapping.TypeDesc.CollapseWhitespace) ilg.Ldarg(0); LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); if (mapping.TypeDesc.CollapseWhitespace) { MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, null, new Type[] { typeof(string) }, null )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } else { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_method = typeof(XmlReader).GetMethod( source == "Reader.Value" ? "get_Value" : "ReadElementContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; if (mapping.TypeDesc.CollapseWhitespace) ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_method); if (mapping.TypeDesc.CollapseWhitespace) { MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } } else { Type argType = source == "false" ? typeof(bool) : typeof(string); MethodInfo ToXXX; if (mapping.TypeDesc.HasCustomFormatter) { // Only these methods below that is non Static and need to ldarg("this") for Call. BindingFlags bindingFlags = CodeGenerator.StaticBindingFlags; if ((mapping.TypeDesc.FormatterName == "ByteArrayBase64" && source == "false") || (mapping.TypeDesc.FormatterName == "ByteArrayHex" && source == "false") || (mapping.TypeDesc.FormatterName == "XmlQualifiedName")) { bindingFlags = CodeGenerator.InstanceBindingFlags; ilg.Ldarg(0); } ToXXX = typeof(XmlSerializationReader).GetMethod( $"To{mapping.TypeDesc.FormatterName}", bindingFlags, new Type[] { argType } )!; } else { ToXXX = typeof(XmlConvert).GetMethod( $"To{mapping.TypeDesc.FormatterName}", CodeGenerator.StaticBindingFlags, new Type[] { argType } )!; } if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); } else if (source == "Reader.Value") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); } else if (source == "vals[i]") { LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); } else { System.Diagnostics.Debug.Assert(source == "false"); ilg.Ldc(false); } ilg.Call(ToXXX); } } private string? MakeUnique(EnumMapping mapping, string name) { string uniqueName = name; EnumMapping? m; if (Enums.TryGetValue(uniqueName, out m)) { if (m == mapping) { // we already have created the hashtable return null; } int i = 0; while (m != null) { i++; uniqueName = name + i.ToString(CultureInfo.InvariantCulture); Enums.TryGetValue(uniqueName, out m); } } Enums.Add(uniqueName, mapping); return uniqueName; } [RequiresUnreferencedCode("calls LoadMember")] private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBuilder? get_TableName) { get_TableName = null; CodeIdentifier.CheckValidIdentifier(typeName); string? propName = MakeUnique(mapping, $"{typeName}Values"); if (propName == null) return CodeIdentifier.GetCSharpName(typeName); string memberName = MakeUnique(mapping, $"_{propName}")!; propName = CodeIdentifier.GetCSharpName(propName); FieldBuilder fieldBuilder = this.typeBuilder.DefineField( memberName, typeof(Hashtable), FieldAttributes.Private ); PropertyBuilder propertyBuilder = this.typeBuilder.DefineProperty( propName, PropertyAttributes.None, CallingConventions.HasThis, typeof(Hashtable), null, null, null, null, null); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(Hashtable), $"get_{propName}", Type.EmptyTypes, Array.Empty<string>(), MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.SpecialName); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); ilg.If(Cmp.EqualTo); ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; LocalBuilder hLoc = ilg.DeclareLocal(typeof(Hashtable), "h"); ilg.New(Hashtable_ctor); ilg.Stloc(hLoc); ConstantMapping[] constants = mapping.Constants!; MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } )!; for (int i = 0; i < constants.Length; i++) { ilg.Ldloc(hLoc); ilg.Ldstr(GetCSharpString(constants[i].XmlName)); ilg.Ldc(Enum.ToObject(mapping.TypeDesc!.Type!, constants[i].Value)); ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long)); ilg.ConvertValue(typeof(long), typeof(object)); ilg.Call(Hashtable_Add); } ilg.Ldarg(0); ilg.Ldloc(hLoc); ilg.StoreMember(fieldBuilder); ilg.EndIf(); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); get_TableName = ilg.EndMethod(); propertyBuilder.SetGetMethod(get_TableName!); return propName; } [RequiresUnreferencedCode("calls WriteHashtable")] private void WriteEnumMethod(EnumMapping mapping) { MethodBuilder? get_TableName = null; if (mapping.IsFlags) WriteHashtable(mapping, mapping.TypeDesc!.Name, out get_TableName); string? methodName; MethodNames.TryGetValue(mapping, out methodName); string fullTypeName = mapping.TypeDesc!.CSharpName; List<Type> argTypes = new List<Type>(); List<string> argNames = new List<string>(); Type returnType; Type underlyingType; returnType = mapping.TypeDesc.Type!; underlyingType = Enum.GetUnderlyingType(returnType); argTypes.Add(typeof(string)); argNames.Add("s"); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( returnType, GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); ConstantMapping[] constants = mapping.Constants!; if (mapping.IsFlags) { { MethodInfo XmlSerializationReader_ToEnum = typeof(XmlSerializationReader).GetMethod( "ToEnum", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(Hashtable), typeof(string) } )!; ilg.Ldarg("s"); ilg.Ldarg(0); Debug.Assert(get_TableName != null); ilg.Call(get_TableName); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_ToEnum); // XmlSerializationReader_ToEnum return long! if (underlyingType != typeof(long)) { ilg.ConvertValue(typeof(long), underlyingType); } ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } } else { List<Label> caseLabels = new List<Label>(); List<object> retValues = new List<object>(); Label defaultLabel = ilg.DefineLabel(); Label endSwitchLabel = ilg.DefineLabel(); // This local is necessary; otherwise, it becomes if/else LocalBuilder localTmp = ilg.GetTempLocal(typeof(string)); ilg.Ldarg("s"); ilg.Stloc(localTmp); ilg.Ldloc(localTmp); ilg.Brfalse(defaultLabel); var cases = new HashSet<string>(); for (int i = 0; i < constants.Length; i++) { ConstantMapping c = constants[i]; CodeIdentifier.CheckValidIdentifier(c.Name); if (cases.Add(c.XmlName)) { Label caseLabel = ilg.DefineLabel(); ilg.Ldloc(localTmp); ilg.Ldstr(GetCSharpString(c.XmlName)); MethodInfo String_op_Equality = typeof(string).GetMethod( "op_Equality", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Call(String_op_Equality); ilg.Brtrue(caseLabel); caseLabels.Add(caseLabel); retValues.Add(Enum.ToObject(mapping.TypeDesc.Type!, c.Value)); } } ilg.Br(defaultLabel); // Case bodies for (int i = 0; i < caseLabels.Count; i++) { ilg.MarkLabel(caseLabels[i]); ilg.Ldc(retValues[i]); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } MethodInfo XmlSerializationReader_CreateUnknownConstantException = typeof(XmlSerializationReader).GetMethod( "CreateUnknownConstantException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(Type) } )!; // Default body ilg.MarkLabel(defaultLabel); ilg.Ldarg(0); ilg.Ldarg("s"); // typeof(..) ilg.Ldc(mapping.TypeDesc.Type!); ilg.Call(XmlSerializationReader_CreateUnknownConstantException); ilg.Throw(); // End switch ilg.MarkLabel(endSwitchLabel); } ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls WriteQNameEqual")] private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string returnTypeName) { for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { ilg.InitElseIf(); WriteQNameEqual("xsiType", derived.TypeName, derived.Namespace); ilg.AndIf(); string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc!.Name)); #endif List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); if (derived.TypeDesc!.IsNullable) { ilg.Ldarg("isNullable"); argTypes.Add(typeof(bool)); } ilg.Ldc(false); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, derived.TypeDesc.Type, argTypes.ToArray() ); ilg.Call(methodBuilder); ilg.ConvertValue(methodBuilder.ReturnType, ilg.ReturnLocal.LocalType); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); WriteDerivedTypes(derived, isTypedReturn, returnTypeName); } } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteEnumAndArrayTypes() { foreach (TypeScope scope in Scopes) { foreach (Mapping m in scope.TypeMappings) { if (m is EnumMapping) { EnumMapping mapping = (EnumMapping)m; ilg.InitElseIf(); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); ilg.AndIf(); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif LocalBuilder eLoc = ilg.DeclareOrGetLocal(typeof(object), "e"); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); ilg.Call(XmlSerializationReader_CollapseWhitespace); ilg.Call(methodBuilder); ilg.ConvertValue(methodBuilder.ReturnType, eLoc.LocalType); ilg.Stloc(eLoc); MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.Ldloc(eLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); // Caller own calling ilg.EndIf(); } else if (m is ArrayMapping) { ArrayMapping mapping = (ArrayMapping)m; if (mapping.TypeDesc!.HasDefaultConstructor) { ilg.InitElseIf(); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); ilg.AndIf(); ilg.EnterScope(); MemberMapping memberMapping = new MemberMapping(); memberMapping.TypeDesc = mapping.TypeDesc; memberMapping.Elements = mapping.Elements; string aVar = "a"; string zVar = "z"; Member member = new Member(this, aVar, zVar, 0, memberMapping); TypeDesc td = mapping.TypeDesc; LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type!, aVar); if (mapping.TypeDesc.IsValueType) { RaCodeGen.ILGenForCreateInstance(ilg, td.Type!, false, false); } else ilg.Load(null); ilg.Stloc(aLoc); WriteArray(member.Source, member.ArrayName, mapping, false, false, -1, 0); ilg.Ldloc(aLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.ExitScope(); // Caller own calling ilg.EndIf(); } } } } } [RequiresUnreferencedCode("calls WriteElement")] private void WriteNullableMethod(NullableMapping nullableMapping) { string? methodName; MethodNames.TryGetValue(nullableMapping, out methodName); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( nullableMapping.TypeDesc!.Type!, GetMethodBuilder(methodName!), new Type[] { typeof(bool) }, new string[] { "checkType" }, CodeGenerator.PrivateMethodAttributes); LocalBuilder oLoc = ilg.DeclareLocal(nullableMapping.TypeDesc.Type!, "o"); ilg.LoadAddress(oLoc); ilg.InitObj(nullableMapping.TypeDesc.Type!); MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes)!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); { ilg.Ldloc(oLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); ElementAccessor element = new ElementAccessor(); element.Mapping = nullableMapping.BaseMapping; element.Any = false; element.IsNullable = nullableMapping.BaseMapping!.TypeDesc!.IsNullable; WriteElement("o", null, null, element, null, null, false, false, -1, -1); ilg.Ldloc(oLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls WriteLiteralStructMethod")] private void WriteStructMethod(StructMapping structMapping) { WriteLiteralStructMethod(structMapping); } [RequiresUnreferencedCode("calls WriteEnumAndArrayTypes")] private void WriteLiteralStructMethod(StructMapping structMapping) { string? methodName; MethodNames.TryGetValue(structMapping, out methodName); string typeName = structMapping.TypeDesc!.CSharpName; ilg = new CodeGenerator(this.typeBuilder); List<Type> argTypes = new List<Type>(); List<string> argNames = new List<string>(); if (structMapping.TypeDesc.IsNullable) { argTypes.Add(typeof(bool)); argNames.Add("isNullable"); } argTypes.Add(typeof(bool)); argNames.Add("checkType"); ilg.BeginMethod( structMapping.TypeDesc.Type!, GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); LocalBuilder locXsiType = ilg.DeclareLocal(typeof(XmlQualifiedName), "xsiType"); LocalBuilder locIsNull = ilg.DeclareLocal(typeof(bool), "isNull"); MethodInfo XmlSerializationReader_GetXsiType = typeof(XmlSerializationReader).GetMethod( "GetXsiType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg("checkType"); ilg.Brtrue(labelTrue); ilg.Load(null); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_GetXsiType); ilg.MarkLabel(labelEnd); ilg.Stloc(locXsiType); ilg.Ldc(false); ilg.Stloc(locIsNull); if (structMapping.TypeDesc.IsNullable) { ilg.Ldarg("isNullable"); ilg.If(); { ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.Stloc(locIsNull); } ilg.EndIf(); } ilg.Ldarg("checkType"); ilg.If(); // if (checkType) if (structMapping.TypeDesc.IsRoot) { ilg.Ldloc(locIsNull); ilg.If(); ilg.Ldloc(locXsiType); ilg.Load(null); ilg.If(Cmp.NotEqualTo); MethodInfo XmlSerializationReader_ReadTypedNull = typeof(XmlSerializationReader).GetMethod( "ReadTypedNull", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedNull); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.Else(); if (structMapping.TypeDesc.IsValueType) { throw Globals.NotSupported(SR.Arg_NeverValueType); } else { ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); // if (xsiType != null) ilg.EndIf(); // if (isNull) } ilg.Ldloc(typeof(XmlQualifiedName), "xsiType"); ilg.Load(null); ilg.Ceq(); if (!structMapping.TypeDesc.IsRoot) { labelTrue = ilg.DefineLabel(); labelEnd = ilg.DefineLabel(); // xsiType == null ilg.Brtrue(labelTrue); WriteQNameEqual("xsiType", structMapping.TypeName, structMapping.Namespace); // Bool result for WriteQNameEqual is on the stack ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); } ilg.If(); // if (xsiType == null if (structMapping.TypeDesc.IsRoot) { ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; MethodInfo XmlSerializationReader_ReadTypedPrimitive = typeof(XmlSerializationReader).GetMethod( "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } )!; ilg.Ldarg(0); ilg.Ldstr(Soap.UrType); ilg.Ldstr(XmlSchema.Namespace); ilg.New(XmlQualifiedName_ctor); ilg.Call(XmlSerializationReader_ReadTypedPrimitive); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } WriteDerivedTypes(structMapping, !structMapping.TypeDesc.IsRoot, typeName); if (structMapping.TypeDesc.IsRoot) WriteEnumAndArrayTypes(); ilg.Else(); // if (xsiType == null if (structMapping.TypeDesc.IsRoot) { MethodInfo XmlSerializationReader_ReadTypedPrimitive = typeof(XmlSerializationReader).GetMethod( "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedPrimitive); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } else { MethodInfo XmlSerializationReader_CreateUnknownTypeException = typeof(XmlSerializationReader).GetMethod( "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_CreateUnknownTypeException); ilg.Throw(); } ilg.EndIf(); // if (xsiType == null ilg.EndIf(); // checkType if (structMapping.TypeDesc.IsNullable) { ilg.Ldloc(typeof(bool), "isNull"); ilg.If(); { ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); } if (structMapping.TypeDesc.IsAbstract) { MethodInfo XmlSerializationReader_CreateAbstractTypeException = typeof(XmlSerializationReader).GetMethod( "CreateAbstractTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(structMapping.TypeName)); ilg.Ldstr(GetCSharpString(structMapping.Namespace)); ilg.Call(XmlSerializationReader_CreateAbstractTypeException); ilg.Throw(); } else { if (structMapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(structMapping.TypeDesc.Type)) { MethodInfo XmlSerializationReader_set_DecodeName = typeof(XmlSerializationReader).GetMethod( "set_DecodeName", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_DecodeName); } WriteCreateMapping(structMapping, "o"); LocalBuilder oLoc = ilg.GetLocal("o"); // this method populates the memberInfos dictionary based on the structMapping MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping, memberInfos); Member? anyText = null; Member? anyElement = null; Member? anyAttribute = null; bool isSequence = structMapping.HasExplicitSequence(); var arraysToDeclareList = new List<Member>(mappings.Length); var arraysToSetList = new List<Member>(mappings.Length); var allMembersList = new List<Member>(mappings.Length); for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; CodeIdentifier.CheckValidIdentifier(mapping.Name); string source = RaCodeGen.GetStringForMember("o", mapping.Name, structMapping.TypeDesc); Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) member.ParamsReadSource = $"paramsRead[{i}]"; member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", $"{mapping.Name}Specified", structMapping.TypeDesc); if (mapping.Text != null) anyText = member; if (mapping.Attribute != null && mapping.Attribute.Any) anyAttribute = member; if (!isSequence) { // find anyElement if present. for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { anyElement = member; break; } } } else if (mapping.IsParticle && !mapping.IsSequence) { StructMapping? declaringMapping; structMapping.FindDeclaringMapping(mapping, out declaringMapping, structMapping.TypeName); throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } if (mapping.Attribute == null && mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) { Member arrayMember = new Member(this, source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); arrayMember.CheckSpecifiedSource = member.CheckSpecifiedSource; allMembersList.Add(arrayMember); } else { allMembersList.Add(member); } if (mapping.TypeDesc.IsArrayLike) { arraysToDeclareList.Add(member); if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.ParamsReadSource = null; // flat arrays -- don't want to count params read. if (member != anyText && member != anyElement) { arraysToSetList.Add(member); } } else if (!mapping.TypeDesc.IsArray) { member.ParamsReadSource = null; // collection } } } if (anyElement != null) arraysToSetList.Add(anyElement); if (anyText != null && anyText != anyElement) arraysToSetList.Add(anyText); Member[] arraysToDeclare = arraysToDeclareList.ToArray(); Member[] arraysToSet = arraysToSetList.ToArray(); Member[] allMembers = allMembersList.ToArray(); WriteMemberBegin(arraysToDeclare); WriteParamsRead(mappings.Length); WriteAttributes(allMembers, anyAttribute, "UnknownNode", oLoc); if (anyAttribute != null) WriteMemberEnd(arraysToDeclare); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToElement = typeof(XmlReader).GetMethod( "MoveToElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); ilg.Pop(); MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); WriteMemberEnd(arraysToSet); ilg.Ldloc(oLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.EndIf(); MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); if (IsSequence(allMembers)) { ilg.Ldc(0); ilg.Stloc(typeof(int), "state"); } WriteWhileNotLoopStart(); string unknownNode = $"UnknownNode((object)o, {ExpectedElements(allMembers)});"; WriteMemberElements(allMembers, unknownNode, unknownNode, anyElement, anyText); MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); WriteMemberEnd(arraysToSet); MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.Ldloc(structMapping.TypeDesc.Type!, "o"); ilg.Stloc(ilg.ReturnLocal); } ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls LoadMember")] private void WriteQNameEqual(string source, string? name, string? ns) { WriteID(name); WriteID(ns); // This api assume the source is local member of XmlQualifiedName type // It leaves bool result on the stack MethodInfo XmlQualifiedName_get_Name = typeof(XmlQualifiedName).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlQualifiedName_get_Namespace = typeof(XmlQualifiedName).GetMethod( "get_Namespace", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelEnd = ilg.DefineLabel(); Label labelFalse = ilg.DefineLabel(); LocalBuilder sLoc = ilg.GetLocal(source); ilg.Ldloc(sLoc); ilg.Call(XmlQualifiedName_get_Name); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[name ?? string.Empty]); ilg.Bne(labelFalse); ilg.Ldloc(sLoc); ilg.Call(XmlQualifiedName_get_Namespace); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[ns ?? string.Empty]); ilg.Ceq(); ilg.Br_S(labelEnd); ilg.MarkLabel(labelFalse); ilg.Ldc(false); ilg.MarkLabel(labelEnd); } [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WriteXmlNodeEqual(string source, string name, string? ns) { WriteXmlNodeEqual(source, name, ns, true); } [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WriteXmlNodeEqual(string source, string name, string? ns, bool doAndIf) { bool isNameNullOrEmpty = string.IsNullOrEmpty(name); if (!isNameNullOrEmpty) { WriteID(name); } WriteID(ns); // Only support Reader and XmlSerializationReaderReader only System.Diagnostics.Debug.Assert(source == "Reader"); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( $"get_{source}", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NamespaceURI = typeof(XmlReader).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); if (!isNameNullOrEmpty) { ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_LocalName); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[name ?? string.Empty]); ilg.Bne(labelFalse); } ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NamespaceURI); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[ns ?? string.Empty]); ilg.Ceq(); if (!isNameNullOrEmpty) { ilg.Br_S(labelEnd); ilg.MarkLabel(labelFalse); ilg.Ldc(false); ilg.MarkLabel(labelEnd); } if (doAndIf) ilg.AndIf(); } private void WriteID(string? name) { if (name == null) { //Writer.Write("null"); //return; name = ""; } if (!_idNames.ContainsKey(name)) { string? idName = NextIdName(name); _idNames.Add(name, idName); _idNameFields.Add(name, this.typeBuilder.DefineField(idName, typeof(string), FieldAttributes.Private)); } } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteAttributes(Member[] members, Member? anyAttribute, string elseCall, LocalBuilder firstParam) { int count = 0; Member? xmlnsMember = null; var attributes = new List<AttributeAccessor>(); // Condition do at the end, so C# looks the same MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToNextAttribute = typeof(XmlReader).GetMethod( "MoveToNextAttribute", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.WhileBegin(); for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.Mapping.Xmlns != null) { xmlnsMember = member; continue; } if (member.Mapping.Ignore) continue; AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; attributes.Add(attribute); if (count++ > 0) ilg.InitElseIf(); else ilg.InitIf(); if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource); ilg.Ldc(false); ilg.AndIf(Cmp.EqualTo); } if (attribute.IsSpecialXmlNamespace) { WriteXmlNodeEqual("Reader", attribute.Name, XmlReservedNs.NsXml); } else WriteXmlNodeEqual("Reader", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : ""); WriteAttribute(member); } if (count > 0) ilg.InitElseIf(); else ilg.InitIf(); if (xmlnsMember != null) { MethodInfo XmlSerializationReader_IsXmlnsAttribute = typeof(XmlSerializationReader).GetMethod( "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Name); ilg.Call(XmlSerializationReader_IsXmlnsAttribute); ilg.Ldc(true); ilg.AndIf(Cmp.EqualTo); ILGenLoad(xmlnsMember.Source); ilg.Load(null); ilg.If(Cmp.EqualTo); WriteSourceBegin(xmlnsMember.Source); ConstructorInfo ctor = xmlnsMember.Mapping.TypeDesc!.Type!.GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); WriteSourceEnd(xmlnsMember.Source, xmlnsMember.Mapping.TypeDesc.Type!); ilg.EndIf(); // if (xmlnsMember.Source == null Label labelEqual5 = ilg.DefineLabel(); Label labelEndLength = ilg.DefineLabel(); MethodInfo Add = xmlnsMember.Mapping.TypeDesc.Type!.GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; MethodInfo String_get_Length = typeof(string).GetMethod( "get_Length", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ILGenLoad(xmlnsMember.ArraySource, xmlnsMember.Mapping.TypeDesc.Type); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Name); ilg.Call(String_get_Length); ilg.Ldc(5); ilg.Beq(labelEqual5); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_LocalName); ilg.Br(labelEndLength); ilg.MarkLabel(labelEqual5); ilg.Ldstr(string.Empty); ilg.MarkLabel(labelEndLength); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); ilg.Call(Add); ilg.Else(); } else { MethodInfo XmlSerializationReader_IsXmlnsAttribute = typeof(XmlSerializationReader).GetMethod( "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Name); ilg.Call(XmlSerializationReader_IsXmlnsAttribute); ilg.Ldc(false); ilg.AndIf(Cmp.EqualTo); } if (anyAttribute != null) { LocalBuilder localAttr = ilg.DeclareOrGetLocal(typeof(XmlAttribute), "attr"); MethodInfo XmlSerializationReader_get_Document = typeof(XmlSerializationReader).GetMethod( "get_Document", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlDocument_ReadNode = typeof(XmlDocument).GetMethod( "ReadNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlReader) } )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlDocument_ReadNode); ilg.ConvertValue(XmlDocument_ReadNode.ReturnType, localAttr.LocalType); ilg.Stloc(localAttr); MethodInfo XmlSerializationReader_ParseWsdlArrayType = typeof(XmlSerializationReader).GetMethod( "ParseWsdlArrayType", CodeGenerator.InstanceBindingFlags, new Type[] { localAttr.LocalType } )!; ilg.Ldarg(0); ilg.Ldloc(localAttr); ilg.Call(XmlSerializationReader_ParseWsdlArrayType); WriteAttribute(anyAttribute); } else { List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); argTypes.Add(typeof(object)); ilg.Ldloc(firstParam); ilg.ConvertValue(firstParam.LocalType, typeof(object)); if (attributes.Count > 0) { string qnames = ""; for (int i = 0; i < attributes.Count; i++) { AttributeAccessor attribute = attributes[i]; if (i > 0) qnames += ", "; qnames += attribute.IsSpecialXmlNamespace ? XmlReservedNs.NsXml : $"{(attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "")}:{attribute.Name}"; } argTypes.Add(typeof(string)); ilg.Ldstr(qnames); } System.Diagnostics.Debug.Assert(elseCall == "UnknownNode"); MethodInfo elseCallMethod = typeof(XmlSerializationReader).GetMethod( elseCall, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() )!; ilg.Call(elseCallMethod); } ilg.EndIf(); ilg.WhileBeginCondition(); { ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToNextAttribute); } ilg.WhileEndCondition(); ilg.WhileEnd(); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteAttribute(Member member) { AttributeAccessor attribute = member.Mapping.Attribute!; if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); ilg.Ldloc("attr"); WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } else if (special.TypeDesc.CanBeAttributeValue) { LocalBuilder attrLoc = ilg.GetLocal("attr"); ilg.Ldloc(attrLoc); // to get code compat if (attrLoc.LocalType == typeof(XmlAttribute)) { ilg.Load(null); ilg.Cne(); } else ilg.IsInst(typeof(XmlAttribute)); ilg.If(); WriteSourceBegin(member.ArraySource); ilg.Ldloc(attrLoc); ilg.ConvertValue(attrLoc.LocalType, typeof(XmlAttribute)); WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); ilg.EndIf(); } else throw new InvalidOperationException(SR.XmlInternalError); } else { if (attribute.IsList) { LocalBuilder locListValues = ilg.DeclareOrGetLocal(typeof(string), "listValues"); LocalBuilder locVals = ilg.DeclareOrGetLocal(typeof(string[]), "vals"); MethodInfo String_Split = typeof(string).GetMethod( "Split", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(char[]) } )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); ilg.Stloc(locListValues); ilg.Ldloc(locListValues); ilg.Load(null); ilg.Call(String_Split); ilg.Stloc(locVals); LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), "i"); ilg.For(localI, 0, locVals); string attributeSource = GetArraySource(member.Mapping.TypeDesc!, member.ArrayName); WriteSourceBegin(attributeSource); WritePrimitive(attribute.Mapping!, "vals[i]"); WriteSourceEnd(attributeSource, member.Mapping.TypeDesc!.ArrayElementTypeDesc!.Type!); ilg.EndFor(); } else { WriteSourceBegin(member.ArraySource); WritePrimitive(attribute.Mapping!, attribute.IsList ? "vals[i]" : "Reader.Value"); WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } } if (member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite && member.CheckSpecifiedSource != null && member.CheckSpecifiedSource.Length > 0) { ILGenSet(member.CheckSpecifiedSource, true); } if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource, true); } } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteMemberBegin(Member[] members) { for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.IsArrayLike) { string a = member.ArrayName; string c = $"c{a}"; TypeDesc typeDesc = member.Mapping.TypeDesc!; if (member.Mapping.TypeDesc!.IsArray) { WriteArrayLocalDecl(typeDesc.CSharpName, a, "null", typeDesc); ilg.Ldc(0); ilg.Stloc(typeof(int), c); if (member.Mapping.ChoiceIdentifier != null) { WriteArrayLocalDecl($"{member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName}[]", member.ChoiceArrayName, "null", member.Mapping.ChoiceIdentifier.Mapping.TypeDesc); ilg.Ldc(0); ilg.Stloc(typeof(int), $"c{member.ChoiceArrayName}"); } } else { if (member.Source[member.Source.Length - 1] == '(' || member.Source[member.Source.Length - 1] == '{') { WriteCreateInstance(a, typeDesc.CannotNew, typeDesc.Type!); WriteSourceBegin(member.Source); ilg.Ldloc(ilg.GetLocal(a)); WriteSourceEnd(member.Source, typeDesc.Type!); } else { if (member.IsList && !member.Mapping.ReadOnly && member.Mapping.TypeDesc.IsNullable) { // we need to new the Collections and ArrayLists ILGenLoad(member.Source, typeof(object)); ilg.Load(null); ilg.If(Cmp.EqualTo); if (!member.Mapping.TypeDesc.HasDefaultConstructor) { MethodInfo XmlSerializationReader_CreateReadOnlyCollectionException = typeof(XmlSerializationReader).GetMethod( "CreateReadOnlyCollectionException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(member.Mapping.TypeDesc.CSharpName)); ilg.Call(XmlSerializationReader_CreateReadOnlyCollectionException); ilg.Throw(); } else { WriteSourceBegin(member.Source); RaCodeGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type!, typeDesc.CannotNew, true); WriteSourceEnd(member.Source, member.Mapping.TypeDesc.Type!); } ilg.EndIf(); // if ((object)(member.Source) == null } WriteLocalDecl(a, new SourceInfo(member.Source, member.Source, member.Mapping.MemberInfo, member.Mapping.TypeDesc.Type, ilg)); } } } } } private string ExpectedElements(Member[] members) { if (IsSequence(members)) return "null"; string qnames = string.Empty; bool firstElement = true; for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.Mapping.Xmlns != null) continue; if (member.Mapping.Ignore) continue; if (member.Mapping.IsText || member.Mapping.IsAttribute) continue; ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement) qnames += ", "; qnames += $"{ns}:{e.Name}"; firstElement = false; } } return ReflectionAwareILGen.GetQuotedCSharpString(qnames); } [RequiresUnreferencedCode("calls WriteMemberElementsIf")] private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member? anyElement, Member? anyText) { if (anyText != null) { ilg.Load(null); ilg.Stloc(typeof(string), "tmp"); } MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; int XmlNodeType_Element = 1; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType_Element); ilg.If(Cmp.EqualTo); WriteMemberElementsIf(members, anyElement, elementElseString); if (anyText != null) WriteMemberText(anyText, elseString); ilg.Else(); ILGenElseString(elseString); ilg.EndIf(); } [RequiresUnreferencedCode("calls WriteText")] private void WriteMemberText(Member anyText, string elseString) { ilg.InitElseIf(); Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.Text); ilg.Ceq(); ilg.Brtrue(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.CDATA); ilg.Ceq(); ilg.Brtrue(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.Whitespace); ilg.Ceq(); ilg.Brtrue(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.SignificantWhitespace); ilg.Ceq(); ilg.Br(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); ilg.AndIf(); if (anyText != null) { WriteText(anyText); } Debug.Assert(anyText != null); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteText(Member member) { TextAccessor text = member.Mapping.Text!; if (text.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); switch (special.TypeDesc!.Kind) { case TypeKind.Node: MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlSerializationReader_get_Document = typeof(XmlSerializationReader).GetMethod( "get_Document", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlDocument_CreateTextNode = typeof(XmlDocument).GetMethod( "CreateTextNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); ilg.Call(XmlDocument_CreateTextNode); break; default: throw new InvalidOperationException(SR.XmlInternalError); } WriteSourceEnd(member.ArraySource, special.TypeDesc.Type!); } else { if (member.IsArrayLike) { WriteSourceBegin(member.ArraySource); if (text.Mapping!.TypeDesc!.CollapseWhitespace) { ilg.Ldarg(0); // for calling CollapseWhitespace } else { } MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); if (text.Mapping.TypeDesc.CollapseWhitespace) { MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } else { if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { LocalBuilder tmpLoc = ilg.GetLocal("tmp"); MethodInfo XmlSerializationReader_ReadString = typeof(XmlSerializationReader).GetMethod( "ReadString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldloc(tmpLoc); ilg.Ldc(text.Mapping.TypeDesc!.CollapseWhitespace); ilg.Call(XmlSerializationReader_ReadString); ilg.Stloc(tmpLoc); WriteSourceBegin(member.ArraySource); ilg.Ldloc(tmpLoc); } else { WriteSourceBegin(member.ArraySource); WritePrimitive(text.Mapping, "Reader.ReadString()"); } } WriteSourceEnd(member.ArraySource, text.Mapping.TypeDesc.Type!); } } [RequiresUnreferencedCode("calls WriteElement")] private void WriteMemberElementsElse(Member? anyElement, string elementElseString) { if (anyElement != null) { ElementAccessor[] elements = anyElement.Mapping.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; if (element.Any && element.Name.Length == 0) { WriteElement(anyElement.ArraySource, anyElement.ArrayName, anyElement.ChoiceArraySource, element, anyElement.Mapping.ChoiceIdentifier, anyElement.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? anyElement.CheckSpecifiedSource : null, false, false, -1, i); break; } } } else { ILGenElementElseString(elementElseString); } } private bool IsSequence(Member[] members) { for (int i = 0; i < members.Length; i++) { if (members[i].Mapping.IsParticle && members[i].Mapping.IsSequence) return true; } return false; } [RequiresUnreferencedCode("calls WriteElement")] private void WriteMemberElementsIf(Member[] members, Member? anyElement, string elementElseString) { int count = 0; bool isSequence = IsSequence(members); int cases = 0; for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.Mapping.Xmlns != null) continue; if (member.Mapping.Ignore) continue; if (isSequence && (member.Mapping.IsText || member.Mapping.IsAttribute)) continue; bool firstElement = true; ChoiceIdentifierAccessor? choice = member.Mapping.ChoiceIdentifier; ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement || (!isSequence && count > 0)) { ilg.InitElseIf(); } else if (isSequence) { if (cases > 0) ilg.InitElseIf(); else ilg.InitIf(); ilg.Ldloc("state"); ilg.Ldc(cases); ilg.AndIf(Cmp.EqualTo); ilg.InitIf(); } else { ilg.InitIf(); } count++; firstElement = false; if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource); ilg.Ldc(false); ilg.AndIf(Cmp.EqualTo); } Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); if (member.Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_get_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "get_IsReturnValue", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_IsReturnValue); ilg.Brtrue(labelTrue); } if (isSequence && e.Any && e.AnyNamespaces == null) { ilg.Ldc(true); } else { WriteXmlNodeEqual("Reader", e.Name, ns, false); } if (member.Mapping.IsReturnValue) { ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); } ilg.AndIf(); WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc!.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); if (member.Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_IsReturnValue); } if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource, true); } } if (isSequence) { if (member.IsArrayLike) { ilg.Else(); } else { ilg.EndIf(); } cases++; ilg.Ldc(cases); ilg.Stloc(ilg.GetLocal("state")); if (member.IsArrayLike) { ilg.EndIf(); } } } if (count > 0) { ilg.Else(); } WriteMemberElementsElse(anyElement, elementElseString); if (count > 0) { ilg.EndIf(); } } private string GetArraySource(TypeDesc typeDesc, string arrayName) { return GetArraySource(typeDesc, arrayName, false); } private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef) { string a = arrayName; string c = $"c{a}"; string init = ""; if (multiRef) { init = $"soap = (System.Object[])EnsureArrayIndex(soap, {c}+2, typeof(System.Object)); "; } if (typeDesc.IsArray) { string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; init = $"{init}{a} = ({arrayTypeFullName}[])EnsureArrayIndex({a}, {c}, {RaCodeGen.GetStringForTypeof(arrayTypeFullName)});"; string arraySource = RaCodeGen.GetStringForArrayMember(a, $"{c}++", typeDesc); if (multiRef) { init = $"{init} soap[1] = {a};"; init = $"{init} if (ReadReference(out soap[{c}+2])) {arraySource} = null; else "; } return $"{init}{arraySource}"; } else { return RaCodeGen.GetStringForMethod(arrayName, typeDesc.CSharpName, "Add"); } } [RequiresUnreferencedCode("calls WriteMemberEnd")] private void WriteMemberEnd(Member[] members) { WriteMemberEnd(members, false); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteMemberEnd(Member[] members, bool soapRefs) { for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.IsArrayLike) { TypeDesc typeDesc = member.Mapping.TypeDesc!; if (typeDesc.IsArray) { WriteSourceBegin(member.Source); Debug.Assert(!soapRefs); string a = member.ArrayName; string c = $"c{a}"; MethodInfo XmlSerializationReader_ShrinkArray = typeof(XmlSerializationReader).GetMethod( "ShrinkArray", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type), typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); ilg.Ldc(typeDesc.ArrayElementTypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, typeDesc.Type!); WriteSourceEnd(member.Source, typeDesc.Type!); if (member.Mapping.ChoiceIdentifier != null) { WriteSourceBegin(member.ChoiceSource!); a = member.ChoiceArrayName; c = $"c{a}"; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); ilg.Ldc(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); WriteSourceEnd(member.ChoiceSource!, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); } } else if (typeDesc.IsValueType) { LocalBuilder arrayLoc = ilg.GetLocal(member.ArrayName); WriteSourceBegin(member.Source); ilg.Ldloc(arrayLoc); WriteSourceEnd(member.Source, arrayLoc.LocalType); } } } } private void WriteSourceBeginTyped(string source, TypeDesc? typeDesc) { WriteSourceBegin(source); } private void WriteSourceBegin(string source) { object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { // local address to invoke ctor on WriteSourceEnd ilg.LoadAddress(variable); } return; } // o.@Field if (source.StartsWith("o.@", StringComparison.Ordinal)) { ilg.LdlocAddress(ilg.GetLocal("o")); return; } // a_0_0 = (global::System.Object[])EnsureArrayIndex(a_0_0, ca_0_0, typeof(global::System.Object));a_0_0[ca_0_0++] Regex regex = NewRegex("(?<locA1>[^ ]+) = .+EnsureArrayIndex[(](?<locA2>[^,]+), (?<locI1>[^,]+),[^;]+;(?<locA3>[^[]+)[[](?<locI2>[^+]+)[+][+][]]"); Match match = regex.Match(source); if (match.Success) { Debug.Assert(match.Groups["locA1"].Value == match.Groups["locA2"].Value); Debug.Assert(match.Groups["locA1"].Value == match.Groups["locA3"].Value); Debug.Assert(match.Groups["locI1"].Value == match.Groups["locI2"].Value); LocalBuilder localA = ilg.GetLocal(match.Groups["locA1"].Value); LocalBuilder localI = ilg.GetLocal(match.Groups["locI1"].Value); Type arrayElementType = localA.LocalType.GetElementType()!; MethodInfo XmlSerializationReader_EnsureArrayIndex = typeof(XmlSerializationReader).GetMethod( "EnsureArrayIndex", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type) } )!; ilg.Ldarg(0); ilg.Ldloc(localA); ilg.Ldloc(localI); ilg.Ldc(arrayElementType); ilg.Call(XmlSerializationReader_EnsureArrayIndex); ilg.Castclass(localA.LocalType); ilg.Stloc(localA); // a_0[ca_0++] ilg.Ldloc(localA); ilg.Ldloc(localI); ilg.Dup(); ilg.Ldc(1); ilg.Add(); ilg.Stloc(localI); if (CodeGenerator.IsNullableGenericType(arrayElementType) || arrayElementType.IsValueType) { ilg.Ldelema(arrayElementType); } return; } //"a_0_0.Add(" if (source.EndsWith(".Add(", StringComparison.Ordinal)) { int index = source.LastIndexOf(".Add(", StringComparison.Ordinal); LocalBuilder localA = ilg.GetLocal(source.Substring(0, index)); ilg.LdlocAddress(localA); return; } // p[0] regex = NewRegex("(?<a>[^[]+)[[](?<ia>.+)[]]"); match = regex.Match(source); if (match.Success) { System.Diagnostics.Debug.Assert(ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)).IsArray); ilg.Load(ilg.GetVariable(match.Groups["a"].Value)); ilg.Load(ilg.GetVariable(match.Groups["ia"].Value)); return; } throw Globals.NotSupported($"Unexpected: {source}"); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteSourceEnd(string source, Type elementType) { WriteSourceEnd(source, elementType, elementType); } [RequiresUnreferencedCode("string-based IL generation")] private void WriteSourceEnd(string source, Type elementType, Type stackType) { object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { ilg.Call(varType.GetConstructor(varType.GetGenericArguments())!); } else { Debug.Assert(elementType != null && variable is LocalBuilder); ilg.ConvertValue(stackType, elementType); ilg.ConvertValue(elementType, varType); ilg.Stloc((LocalBuilder)variable); } return; } // o.@Field if (source.StartsWith("o.@", StringComparison.Ordinal)) { Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); MemberInfo memInfo = memberInfos[source.Substring(3)]; ilg.ConvertValue(stackType, memInfo is FieldInfo ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType); ilg.StoreMember(memInfo); return; } // a_0_0 = (global::System.Object[])EnsureArrayIndex(a_0_0, ca_0_0, typeof(global::System.Object));a_0_0[ca_0_0++] Regex regex = NewRegex("(?<locA1>[^ ]+) = .+EnsureArrayIndex[(](?<locA2>[^,]+), (?<locI1>[^,]+),[^;]+;(?<locA3>[^[]+)[[](?<locI2>[^+]+)[+][+][]]"); Match match = regex.Match(source); if (match.Success) { object oVar = ilg.GetVariable(match.Groups["locA1"].Value); Type arrayElementType = ilg.GetVariableType(oVar).GetElementType()!; ilg.ConvertValue(elementType, arrayElementType); if (CodeGenerator.IsNullableGenericType(arrayElementType) || arrayElementType.IsValueType) { ilg.Stobj(arrayElementType); } else { ilg.Stelem(arrayElementType); } return; } //"a_0_0.Add(" if (source.EndsWith(".Add(", StringComparison.Ordinal)) { int index = source.LastIndexOf(".Add(", StringComparison.Ordinal); LocalBuilder localA = ilg.GetLocal(source.Substring(0, index)); Debug.Assert(!localA.LocalType.IsGenericType || (localA.LocalType.GetGenericArguments().Length == 1 && localA.LocalType.GetGenericArguments()[0].IsAssignableFrom(elementType))); MethodInfo Add = localA.LocalType.GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { elementType } )!; Debug.Assert(Add != null); Type addParameterType = Add.GetParameters()[0].ParameterType; ilg.ConvertValue(stackType, addParameterType); ilg.Call(Add); if (Add.ReturnType != typeof(void)) ilg.Pop(); return; } // p[0] regex = NewRegex("(?<a>[^[]+)[[](?<ia>.+)[]]"); match = regex.Match(source); if (match.Success) { Type varType = ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)); System.Diagnostics.Debug.Assert(varType.IsArray); Type varElementType = varType.GetElementType()!; ilg.ConvertValue(stackType, varElementType); ilg.Stelem(varElementType); return; } throw Globals.NotSupported($"Unexpected: {source}"); } [RequiresUnreferencedCode("calls WriteMemberBegin")] private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex, int elementIndex) { MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.IfNot(); MemberMapping memberMapping = new MemberMapping(); memberMapping.Elements = arrayMapping.Elements; memberMapping.TypeDesc = arrayMapping.TypeDesc; memberMapping.ReadOnly = readOnly; if (source.StartsWith("o.@", StringComparison.Ordinal)) { Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); memberMapping.MemberInfo = memberInfos[source.Substring(3)]; } Member member = new Member(this, source, arrayName, elementIndex, memberMapping, false); member.IsNullable = false; //Note, IsNullable is set to false since null condition (xsi:nil) is already handled by 'ReadNull()' Member[] members = new Member[] { member }; WriteMemberBegin(members); Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); if (readOnly) { ilg.Load(ilg.GetVariable(member.ArrayName)); ilg.Load(null); ilg.Beq(labelTrue); } else { } MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); if (readOnly) { ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); } ilg.If(); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Else(); MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); WriteWhileNotLoopStart(); string unknownNode = $"UnknownNode(null, {ExpectedElements(members)});"; WriteMemberElements(members, unknownNode, unknownNode, null, null); MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.EndIf(); WriteMemberEnd(members, false); if (isNullable) { ilg.Else(); member.IsNullable = true; WriteMemberBegin(members); WriteMemberEnd(members); } ilg.EndIf(); } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteElement(string source, string? arrayName, string? choiceSource, ElementAccessor element, ChoiceIdentifierAccessor? choice, string? checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) { if (checkSpecified != null && checkSpecified.Length > 0) { ILGenSet(checkSpecified, true); } if (element.Mapping is ArrayMapping) { WriteArray(source, arrayName, (ArrayMapping)element.Mapping, readOnly, element.IsNullable, fixupIndex, elementIndex); } else if (element.Mapping is NullableMapping) { string? methodName = ReferenceMapping(element.Mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc!.Name)); #endif WriteSourceBegin(source); ilg.Ldarg(0); ilg.Ldc(true); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, // See WriteNullableMethod for different return type logic element.Mapping.TypeDesc!.Type, new Type[] { typeof(bool) } ); ilg.Call(methodBuilder); WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } else if (element.Mapping is PrimitiveMapping) { bool doEndIf = false; if (element.IsNullable) { MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); WriteSourceBegin(source); if (element.Mapping.TypeDesc!.IsValueType) { throw Globals.NotSupported("No such condition. PrimitiveMapping && IsNullable = String, XmlQualifiedName and never IsValueType"); } else { ilg.Load(null); } WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); ilg.Else(); doEndIf = true; } if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Else(); doEndIf = true; } else { } if ((element.Mapping.TypeDesc!.Type == typeof(TimeSpan)) || element.Mapping.TypeDesc!.Type == typeof(DateTimeOffset)) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); WriteSourceBegin(source); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); LocalBuilder tmpLoc = ilg.GetTempLocal(element.Mapping.TypeDesc!.Type); ilg.Ldloca(tmpLoc); ilg.InitObj(element.Mapping.TypeDesc!.Type); ilg.Ldloc(tmpLoc); WriteSourceEnd(source, element.Mapping.TypeDesc.Type); ilg.Else(); WriteSourceBegin(source); WritePrimitive(element.Mapping, "Reader.ReadElementString()"); WriteSourceEnd(source, element.Mapping.TypeDesc.Type); ilg.EndIf(); } else { WriteSourceBegin(source); if (element.Mapping.TypeDesc == QnameTypeDesc) { MethodInfo XmlSerializationReader_ReadElementQualifiedName = typeof(XmlSerializationReader).GetMethod( "ReadElementQualifiedName", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadElementQualifiedName); } else { string readFunc; switch (element.Mapping.TypeDesc.FormatterName) { case "ByteArrayBase64": case "ByteArrayHex": readFunc = "false"; break; default: readFunc = "Reader.ReadElementString()"; break; } WritePrimitive(element.Mapping, readFunc); } WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } if (doEndIf) ilg.EndIf(); } else if (element.Mapping is StructMapping) { TypeMapping mapping = element.Mapping; string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif if (checkForNull) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldloc(arrayName!); ilg.Load(null); ilg.If(Cmp.EqualTo); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Else(); } WriteSourceBegin(source); List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); if (mapping.TypeDesc!.IsNullable) { ilg.Load(element.IsNullable); argTypes.Add(typeof(bool)); } ilg.Ldc(true); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc.Type, argTypes.ToArray() ); ilg.Call(methodBuilder); WriteSourceEnd(source, mapping.TypeDesc.Type!); if (checkForNull) // 'If' begins in checkForNull above ilg.EndIf(); } else if (element.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)element.Mapping; switch (special.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; WriteSourceBeginTyped(source, special.TypeDesc); MethodInfo XmlSerializationReader_ReadXmlXXX = typeof(XmlSerializationReader).GetMethod( isDoc ? "ReadXmlDocument" : "ReadXmlNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(element.Any ? false : true); ilg.Call(XmlSerializationReader_ReadXmlXXX); // See logic in WriteSourceBeginTyped whether or not to castclass. if (special.TypeDesc != null) ilg.Castclass(special.TypeDesc.Type!); WriteSourceEnd(source, special.TypeDesc!.Type!); break; case TypeKind.Serializable: SerializableMapping sm = (SerializableMapping)element.Mapping; // check to see if we need to do the derivation if (sm.DerivedMappings != null) { MethodInfo XmlSerializationReader_GetXsiType = typeof(XmlSerializationReader).GetMethod( "GetXsiType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); LocalBuilder tserLoc = ilg.DeclareOrGetLocal(typeof(XmlQualifiedName), "tser"); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_GetXsiType); ilg.Stloc(tserLoc); ilg.Ldloc(tserLoc); ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); WriteQNameEqual("tser", sm.XsiType!.Name, sm.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); ilg.If(); } WriteSourceBeginTyped(source, sm.TypeDesc!); bool isWrappedAny = !element.Any && IsWildcard(sm); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } )!; ilg.Ldarg(0); RaCodeGen.ILGenForCreateInstance(ilg, sm.TypeDesc!.Type!, sm.TypeDesc.CannotNew, false); if (sm.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) ilg.Ldc(true); ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (sm.TypeDesc != null) ilg.ConvertValue(typeof(IXmlSerializable), sm.TypeDesc.Type!); WriteSourceEnd(source, sm.TypeDesc!.Type!); if (sm.DerivedMappings != null) { WriteDerivedSerializable(sm, sm, source, isWrappedAny); WriteUnknownNode("UnknownNode", "null", null, true); } break; default: throw new InvalidOperationException(SR.XmlInternalError); } } else { throw new InvalidOperationException(SR.XmlInternalError); } if (choice != null) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source)); #endif WriteSourceBegin(choiceSource!); CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping!.TypeDesc!.Type!, choice.MemberIds[elementIndex]); WriteSourceEnd(choiceSource!, choice.Mapping.TypeDesc.Type!); } } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteDerivedSerializable(SerializableMapping head, SerializableMapping? mapping, string source, bool isWrappedAny) { if (mapping == null) return; for (SerializableMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); LocalBuilder tserLoc = ilg.GetLocal("tser"); ilg.InitElseIf(); ilg.Ldloc(tserLoc); ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); WriteQNameEqual("tser", derived.XsiType!.Name, derived.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); ilg.AndIf(); if (derived.Type != null) { if (head.Type!.IsAssignableFrom(derived.Type)) { WriteSourceBeginTyped(source, head.TypeDesc!); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } )!; ilg.Ldarg(0); RaCodeGen.ILGenForCreateInstance(ilg, derived.TypeDesc!.Type!, derived.TypeDesc.CannotNew, false); if (derived.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) ilg.Ldc(true); ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (head.TypeDesc != null) ilg.ConvertValue(typeof(IXmlSerializable), head.TypeDesc.Type!); WriteSourceEnd(source, head.TypeDesc!.Type!); } else { MethodInfo XmlSerializationReader_CreateBadDerivationException = typeof(XmlSerializationReader).GetMethod( "CreateBadDerivationException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(head.XsiType!.Name)); ilg.Ldstr(GetCSharpString(head.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(derived.Type.FullName)); ilg.Ldstr(GetCSharpString(head.Type.FullName)); ilg.Call(XmlSerializationReader_CreateBadDerivationException); ilg.Throw(); } } else { MethodInfo XmlSerializationReader_CreateMissingIXmlSerializableType = typeof(XmlSerializationReader).GetMethod( "CreateMissingIXmlSerializableType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(head.Type!.FullName)); ilg.Call(XmlSerializationReader_CreateMissingIXmlSerializableType); ilg.Throw(); } WriteDerivedSerializable(head, derived, source, isWrappedAny); } } private void WriteWhileNotLoopStart() { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); ilg.WhileBegin(); } private void WriteWhileLoopEnd() { ilg.WhileBeginCondition(); { int XmlNodeType_None = 0; //int XmlNodeType_Element = 1; int XmlNodeType_EndElement = 15; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType_EndElement); ilg.Beq(labelFalse); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType_None); ilg.Cne(); ilg.Br_S(labelEnd); ilg.MarkLabel(labelFalse); ilg.Ldc(false); ilg.MarkLabel(labelEnd); } ilg.WhileEndCondition(); ilg.WhileEnd(); } private void WriteParamsRead(int length) { LocalBuilder paramsRead = ilg.DeclareLocal(typeof(bool[]), "paramsRead"); ilg.NewArray(typeof(bool), length); ilg.Stloc(paramsRead); } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteCreateMapping(TypeMapping mapping, string local) { string fullTypeName = mapping.TypeDesc!.CSharpName; bool ctorInaccessible = mapping.TypeDesc.CannotNew; LocalBuilder loc = ilg.DeclareLocal( mapping.TypeDesc.Type!, local); if (ctorInaccessible) { ilg.BeginExceptionBlock(); } RaCodeGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type!, mapping.TypeDesc.CannotNew, true); ilg.Stloc(loc); if (ctorInaccessible) { ilg.Leave(); WriteCatchException(typeof(MissingMethodException)); MethodInfo XmlSerializationReader_CreateInaccessibleConstructorException = typeof(XmlSerializationReader).GetMethod( "CreateInaccessibleConstructorException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateInaccessibleConstructorException); ilg.Throw(); WriteCatchException(typeof(SecurityException)); MethodInfo XmlSerializationReader_CreateCtorHasSecurityException = typeof(XmlSerializationReader).GetMethod( "CreateCtorHasSecurityException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateCtorHasSecurityException); ilg.Throw(); ilg.EndExceptionBlock(); } } private void WriteCatchException(Type exceptionType) { ilg.BeginCatchBlock(exceptionType); ilg.Pop(); } [RequiresUnreferencedCode("calls WriteArrayLocalDecl")] private void WriteArrayLocalDecl(string typeName, string variableName, string initValue, TypeDesc arrayTypeDesc) { RaCodeGen.WriteArrayLocalDecl(typeName, variableName, new SourceInfo(initValue, initValue, null, arrayTypeDesc.Type, ilg), arrayTypeDesc); } [RequiresUnreferencedCode("calls WriteCreateInstance")] private void WriteCreateInstance(string source, bool ctorInaccessible, Type type) { RaCodeGen.WriteCreateInstance(source, ctorInaccessible, type, ilg); } [RequiresUnreferencedCode("calls WriteLocalDecl")] private void WriteLocalDecl(string variableName, SourceInfo initValue) { RaCodeGen.WriteLocalDecl(variableName, initValue); } private void ILGenElseString(string elseString) { MethodInfo XmlSerializationReader_UnknownNode1 = typeof(XmlSerializationReader).GetMethod( "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } )!; MethodInfo XmlSerializationReader_UnknownNode2 = typeof(XmlSerializationReader).GetMethod( "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(string) } )!; // UnknownNode(null, @":anyType"); Regex regex = NewRegex("UnknownNode[(]null, @[\"](?<qnames>[^\"]*)[\"][)];"); Match match = regex.Match(elseString); if (match.Success) { ilg.Ldarg(0); ilg.Load(null); ilg.Ldstr(match.Groups["qnames"].Value); ilg.Call(XmlSerializationReader_UnknownNode2); return; } // UnknownNode((object)o, @""); regex = NewRegex("UnknownNode[(][(]object[)](?<o>[^,]+), @[\"](?<qnames>[^\"]*)[\"][)];"); match = regex.Match(elseString); if (match.Success) { ilg.Ldarg(0); LocalBuilder localO = ilg.GetLocal(match.Groups["o"].Value); ilg.Ldloc(localO); ilg.ConvertValue(localO.LocalType, typeof(object)); ilg.Ldstr(match.Groups["qnames"].Value); ilg.Call(XmlSerializationReader_UnknownNode2); return; } // UnknownNode((object)o, null); regex = NewRegex("UnknownNode[(][(]object[)](?<o>[^,]+), null[)];"); match = regex.Match(elseString); if (match.Success) { ilg.Ldarg(0); LocalBuilder localO = ilg.GetLocal(match.Groups["o"].Value); ilg.Ldloc(localO); ilg.ConvertValue(localO.LocalType, typeof(object)); ilg.Load(null); ilg.Call(XmlSerializationReader_UnknownNode2); return; } // "UnknownNode((object)o);" regex = NewRegex("UnknownNode[(][(]object[)](?<o>[^)]+)[)];"); match = regex.Match(elseString); if (match.Success) { ilg.Ldarg(0); LocalBuilder localO = ilg.GetLocal(match.Groups["o"].Value); ilg.Ldloc(localO); ilg.ConvertValue(localO.LocalType, typeof(object)); ilg.Call(XmlSerializationReader_UnknownNode1); return; } throw Globals.NotSupported($"Unexpected: {elseString}"); } private void ILGenParamsReadSource(string paramsReadSource) { Regex regex = NewRegex("paramsRead\\[(?<index>[0-9]+)\\]"); Match match = regex.Match(paramsReadSource); if (match.Success) { ilg.LoadArrayElement(ilg.GetLocal("paramsRead"), int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture)); return; } throw Globals.NotSupported($"Unexpected: {paramsReadSource}"); } private void ILGenParamsReadSource(string paramsReadSource, bool value) { Regex regex = NewRegex("paramsRead\\[(?<index>[0-9]+)\\]"); Match match = regex.Match(paramsReadSource); if (match.Success) { ilg.StoreArrayElement(ilg.GetLocal("paramsRead"), int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture), value); return; } throw Globals.NotSupported($"Unexpected: {paramsReadSource}"); } private void ILGenElementElseString(string elementElseString) { if (elementElseString == "throw CreateUnknownNodeException();") { MethodInfo XmlSerializationReader_CreateUnknownNodeException = typeof(XmlSerializationReader).GetMethod( "CreateUnknownNodeException", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_CreateUnknownNodeException); ilg.Throw(); return; } if (elementElseString.StartsWith("UnknownNode(", StringComparison.Ordinal)) { ILGenElseString(elementElseString); return; } throw Globals.NotSupported($"Unexpected: {elementElseString}"); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void ILGenSet(string source, object value) { WriteSourceBegin(source); ilg.Load(value); WriteSourceEnd(source, value == null ? typeof(object) : value.GetType()); } } }
// 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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Security; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Schema; using System.Xml.Extensions; using System.Diagnostics.CodeAnalysis; internal sealed partial class XmlSerializationReaderILGen : XmlSerializationILGen { private readonly Dictionary<string, string> _idNames = new Dictionary<string, string>(); // Mapping name->id_XXXNN field private readonly Dictionary<string, FieldBuilder> _idNameFields = new Dictionary<string, FieldBuilder>(); private Dictionary<string, EnumMapping>? _enums; private int _nextIdNumber; internal Dictionary<string, EnumMapping> Enums { get { if (_enums == null) { _enums = new Dictionary<string, EnumMapping>(); } return _enums; } } private sealed class Member { private readonly string _source; private readonly string _arrayName; private readonly string _arraySource; private readonly string _choiceArrayName; private readonly string? _choiceSource; private readonly string? _choiceArraySource; private readonly MemberMapping _mapping; private readonly bool _isArray; private readonly bool _isList; private bool _isNullable; private int _fixupIndex = -1; private string? _paramsReadSource; private string? _checkSpecifiedSource; internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, null, arrayName, i, mapping, false, null) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, null, arrayName, i, mapping, false, choiceSource) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, arraySource, arrayName, i, mapping, false, null) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, arraySource, arrayName, i, mapping, false, choiceSource) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) : this(outerClass, source, null, arrayName, i, mapping, multiRef, null) { } internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) { _source = source; _arrayName = string.Create(CultureInfo.InvariantCulture, $"{arrayName}_{i}"); _choiceArrayName = $"choice_{_arrayName}"; _choiceSource = choiceSource; if (mapping.TypeDesc!.IsArrayLike) { if (arraySource != null) _arraySource = arraySource; else _arraySource = outerClass.GetArraySource(mapping.TypeDesc, _arrayName, multiRef); _isArray = mapping.TypeDesc.IsArray; _isList = !_isArray; if (mapping.ChoiceIdentifier != null) { _choiceArraySource = outerClass.GetArraySource(mapping.TypeDesc, _choiceArrayName, multiRef); string a = _choiceArrayName; string c = $"c{a}"; string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName; string castString = $"({choiceTypeFullName}[])"; string init = $"{a} = {castString}EnsureArrayIndex({a}, {c}, {outerClass.RaCodeGen.GetStringForTypeof(choiceTypeFullName)});"; _choiceArraySource = init + outerClass.RaCodeGen.GetStringForArrayMember(a, $"{c}++", mapping.ChoiceIdentifier.Mapping.TypeDesc); } else { _choiceArraySource = _choiceSource; } } else { _arraySource = arraySource == null ? source : arraySource; _choiceArraySource = _choiceSource; } _mapping = mapping; } internal MemberMapping Mapping { get { return _mapping; } } internal string Source { get { return _source; } } internal string ArrayName { get { return _arrayName; } } internal string ArraySource { get { return _arraySource; } } internal bool IsList { get { return _isList; } } internal bool IsArrayLike { get { return (_isArray || _isList); } } internal bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } internal int FixupIndex { get { return _fixupIndex; } set { _fixupIndex = value; } } internal string? ParamsReadSource { get { return _paramsReadSource; } set { _paramsReadSource = value; } } internal string? CheckSpecifiedSource { get { return _checkSpecifiedSource; } set { _checkSpecifiedSource = value; } } internal string? ChoiceSource { get { return _choiceSource; } } internal string ChoiceArrayName { get { return _choiceArrayName; } } internal string? ChoiceArraySource { get { return _choiceArraySource; } } } [RequiresUnreferencedCode("Creates XmlSerializationILGen")] internal XmlSerializationReaderILGen(TypeScope[] scopes, string access, string className) : base(scopes, access, className) { } [RequiresUnreferencedCode("calls WriteReflectionInit")] internal void GenerateBegin() { this.typeBuilder = CodeGenerator.CreateTypeBuilder( ModuleBuilder, ClassName, TypeAttributes | TypeAttributes.BeforeFieldInit, typeof(XmlSerializationReader), Type.EmptyTypes); foreach (TypeScope scope in Scopes) { foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping is StructMapping || mapping is EnumMapping || mapping is NullableMapping) MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } RaCodeGen.WriteReflectionInit(scope); } } [RequiresUnreferencedCode("calls WriteStructMethod")] internal override void GenerateMethod(TypeMapping mapping) { if (!GeneratedMethods.Add(mapping)) return; if (mapping is StructMapping) { WriteStructMethod((StructMapping)mapping); } else if (mapping is EnumMapping) { WriteEnumMethod((EnumMapping)mapping); } else if (mapping is NullableMapping) { WriteNullableMethod((NullableMapping)mapping); } } [RequiresUnreferencedCode("calls GenerateReferencedMethods")] internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] types) { GenerateReferencedMethods(); GenerateInitCallbacksMethod(); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod(typeof(void), "InitIDs", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NameTable = typeof(XmlReader).GetMethod( "get_NameTable", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlNameTable_Add = typeof(XmlNameTable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; foreach (string id in _idNames.Keys) { ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NameTable); ilg.Ldstr(GetCSharpString(id)); ilg.Call(XmlNameTable_Add); Debug.Assert(_idNameFields.ContainsKey(id)); ilg.StoreMember(_idNameFields[id]); } ilg.EndMethod(); this.typeBuilder.DefineDefaultConstructor( CodeGenerator.PublicMethodAttributes); Type readerType = this.typeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(readerType.Name, readerType); } [RequiresUnreferencedCode("calls GenerateMembersElement")] internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsReadable) return null; if (!xmlMapping.GenerateSerializer) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); if (xmlMapping is XmlTypeMapping) return GenerateTypeElement((XmlTypeMapping)xmlMapping); else if (xmlMapping is XmlMembersMapping) return GenerateMembersElement((XmlMembersMapping)xmlMapping); else throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } [RequiresUnreferencedCode("calls LoadMember")] private void WriteIsStartTag(string? name, string? ns) { WriteID(name); WriteID(ns); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod( "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[name ?? string.Empty]); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[ns ?? string.Empty]); ilg.Call(XmlReader_IsStartElement); ilg.If(); } [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WriteUnknownNode(string func, string node, ElementAccessor? e, bool anyIfs) { if (anyIfs) { ilg.Else(); } List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); Debug.Assert(node == "null" || node == "(object)p"); if (node == "null") ilg.Load(null); else { object pVar = ilg.GetVariable("p"); ilg.Load(pVar); ilg.ConvertValue(ilg.GetVariableType(pVar), typeof(object)); } argTypes.Add(typeof(object)); if (e != null) { string? expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; expectedElement += ":"; expectedElement += e.Name; ilg.Ldstr(ReflectionAwareILGen.GetCSharpString(expectedElement)); argTypes.Add(typeof(string)); } MethodInfo method = typeof(XmlSerializationReader).GetMethod( func, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() )!; ilg.Call(method); if (anyIfs) { ilg.EndIf(); } } private void GenerateInitCallbacksMethod() { ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod(typeof(void), "InitCallbacks", Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.EndMethod(); } [RequiresUnreferencedCode("calls GenerateLiteralMembersElement")] private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { return GenerateLiteralMembersElement(xmlMembersMapping); } private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { string? choiceSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mappings.Length; j++) { if (mappings[j].Name == member.ChoiceIdentifier.MemberName) { choiceSource = $"p[{j}]"; break; } } #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping.")); #endif } return choiceSource!; } private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) { if (mapping.ChoiceIdentifier == null) return ""; CodeIdentifier.CheckValidIdentifier(mapping.ChoiceIdentifier.MemberName); return RaCodeGen.GetStringForMember(parent, mapping.ChoiceIdentifier.MemberName, parentTypeDesc); } [RequiresUnreferencedCode("calls InitializeValueTypes")] private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(object[]), methodName, Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicMethodAttributes ); ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); LocalBuilder localP = ilg.DeclareLocal(typeof(object[]), "p"); ilg.NewArray(typeof(object), mappings.Length); ilg.Stloc(localP); InitializeValueTypes("p", mappings); if (hasWrapperElement) { WriteWhileNotLoopStart(); WriteIsStartTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""); } Member? anyText = null; Member? anyElement = null; Member? anyAttribute = null; var membersList = new List<Member>(); var textOrArrayMembersList = new List<Member>(); var attributeMembersList = new List<Member>(); for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; string source = $"p[{i}]"; string arraySource = source; if (mapping.Xmlns != null) { arraySource = $"(({mapping.TypeDesc!.CSharpName}){source})"; } string choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); Member anyMember = new Member(this, source, null, "a", i, mapping, choiceSource); if (!mapping.IsSequence) member.ParamsReadSource = $"paramsRead[{i}]"; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) { string nameSpecified = $"{mapping.Name}Specified"; for (int j = 0; j < mappings.Length; j++) { if (mappings[j].Name == nameSpecified) { member.CheckSpecifiedSource = $"p[{j}]"; break; } } } bool foundAnyElement = false; if (mapping.Text != null) anyText = anyMember; if (mapping.Attribute != null && mapping.Attribute.Any) anyAttribute = anyMember; if (mapping.Attribute != null || mapping.Xmlns != null) attributeMembersList.Add(member); else if (mapping.Text != null) textOrArrayMembersList.Add(member); if (!mapping.IsSequence) { for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { anyElement = anyMember; if (mapping.Attribute == null && mapping.Text == null) textOrArrayMembersList.Add(anyMember); foundAnyElement = true; break; } } } if (mapping.Attribute != null || mapping.Text != null || foundAnyElement) membersList.Add(anyMember); else if (mapping.TypeDesc!.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { membersList.Add(anyMember); textOrArrayMembersList.Add(anyMember); } else { if (mapping.TypeDesc.IsArrayLike && !mapping.TypeDesc.IsArray) member.ParamsReadSource = null; // collection membersList.Add(member); } } Member[] members = membersList.ToArray(); Member[] textOrArrayMembers = textOrArrayMembersList.ToArray(); if (members.Length > 0 && members[0].Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(true); ilg.Call(XmlSerializationReader_set_IsReturnValue); } WriteParamsRead(mappings.Length); if (attributeMembersList.Count > 0) { Member[] attributeMembers = attributeMembersList.ToArray(); WriteMemberBegin(attributeMembers); WriteAttributes(attributeMembers, anyAttribute, "UnknownNode", localP); WriteMemberEnd(attributeMembers); MethodInfo XmlReader_MoveToElement = typeof(XmlReader).GetMethod( "MoveToElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); ilg.Pop(); } WriteMemberBegin(textOrArrayMembers); if (hasWrapperElement) { MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); { MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); ilg.WhileContinue(); } ilg.EndIf(); MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); } if (IsSequence(members)) { ilg.Ldc(0); ilg.Stloc(typeof(int), "state"); } WriteWhileNotLoopStart(); string unknownNode = $"UnknownNode((object)p, {ExpectedElements(members)});"; WriteMemberElements(members, unknownNode, unknownNode, anyElement, anyText); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); WriteMemberEnd(textOrArrayMembers); if (hasWrapperElement) { MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); WriteUnknownNode("UnknownNode", "null", element, true); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); } ilg.Ldloc(ilg.GetLocal("p")); ilg.EndMethod(); return methodName; } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { if (!mappings[i].TypeDesc!.IsValueType) continue; LocalBuilder arrayLoc = ilg.GetLocal(arrayName); ilg.Ldloc(arrayLoc); ilg.Ldc(i); RaCodeGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc!.Type!, false, false); ilg.ConvertValue(mappings[i].TypeDesc!.Type!, typeof(object)); ilg.Stelem(arrayLoc.LocalType.GetElementType()!); } } [RequiresUnreferencedCode("calls WriteMemberElements")] private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(object), methodName, Type.EmptyTypes, Array.Empty<string>(), CodeGenerator.PublicMethodAttributes ); LocalBuilder oLoc = ilg.DeclareLocal(typeof(object), "o"); ilg.Load(null); ilg.Stloc(oLoc); MemberMapping member = new MemberMapping(); member.TypeDesc = mapping.TypeDesc; //member.ReadOnly = !mapping.TypeDesc.HasDefaultConstructor; member.Elements = new ElementAccessor[] { element }; Member[] members = new Member[] { new Member(this, "o", "o", "a", 0, member) }; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); string unknownNode = $"UnknownNode(null, {ExpectedElements(members)});"; WriteMemberElements(members, "throw CreateUnknownNodeException();", unknownNode, element.Any ? members[0] : null, null); ilg.Ldloc(oLoc); // for code compat as compiler does ilg.Stloc(ilg.ReturnLocal); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); return methodName; } private string NextMethodName(string name) => string.Create(CultureInfo.InvariantCulture, $"Read{++NextMethodNumber}_{CodeIdentifier.MakeValidInternal(name)}"); private string NextIdName(string name) => string.Create(CultureInfo.InvariantCulture, $"id{++_nextIdNumber}_{CodeIdentifier.MakeValidInternal(name)}"); [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WritePrimitive(TypeMapping mapping, string source) { System.Diagnostics.Debug.Assert(source == "Reader.ReadElementString()" || source == "Reader.ReadString()" || source == "false" || source == "Reader.Value" || source == "vals[i]"); if (mapping is EnumMapping) { string? enumMethodName = ReferenceMapping(mapping); if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc!.Name)); // For enum, its read method (eg. Read1_Gender) could be called multiple times // prior to its declaration. MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, enumMethodName, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); ilg.Ldarg(0); if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); } else if (source == "Reader.Value") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); } else if (source == "vals[i]") { LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); } else if (source == "false") { ilg.Ldc(false); } else { throw Globals.NotSupported($"Unexpected: {source}"); } ilg.Call(methodBuilder); } else if (mapping.TypeDesc == StringTypeDesc) { if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); } else if (source == "Reader.Value") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); } else if (source == "vals[i]") { LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); } else { throw Globals.NotSupported($"Unexpected: {source}"); } } else if (mapping.TypeDesc!.FormatterName == "String") { System.Diagnostics.Debug.Assert(source == "Reader.Value" || source == "Reader.ReadElementString()" || source == "vals[i]"); if (source == "vals[i]") { if (mapping.TypeDesc.CollapseWhitespace) ilg.Ldarg(0); LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); if (mapping.TypeDesc.CollapseWhitespace) { MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, null, new Type[] { typeof(string) }, null )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } else { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_method = typeof(XmlReader).GetMethod( source == "Reader.Value" ? "get_Value" : "ReadElementContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; if (mapping.TypeDesc.CollapseWhitespace) ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_method); if (mapping.TypeDesc.CollapseWhitespace) { MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } } else { Type argType = source == "false" ? typeof(bool) : typeof(string); MethodInfo ToXXX; if (mapping.TypeDesc.HasCustomFormatter) { // Only these methods below that is non Static and need to ldarg("this") for Call. BindingFlags bindingFlags = CodeGenerator.StaticBindingFlags; if ((mapping.TypeDesc.FormatterName == "ByteArrayBase64" && source == "false") || (mapping.TypeDesc.FormatterName == "ByteArrayHex" && source == "false") || (mapping.TypeDesc.FormatterName == "XmlQualifiedName")) { bindingFlags = CodeGenerator.InstanceBindingFlags; ilg.Ldarg(0); } ToXXX = typeof(XmlSerializationReader).GetMethod( $"To{mapping.TypeDesc.FormatterName}", bindingFlags, new Type[] { argType } )!; } else { ToXXX = typeof(XmlConvert).GetMethod( $"To{mapping.TypeDesc.FormatterName}", CodeGenerator.StaticBindingFlags, new Type[] { argType } )!; } if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); } else if (source == "Reader.Value") { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); } else if (source == "vals[i]") { LocalBuilder locVals = ilg.GetLocal("vals"); LocalBuilder locI = ilg.GetLocal("i"); ilg.LoadArrayElement(locVals, locI); } else { System.Diagnostics.Debug.Assert(source == "false"); ilg.Ldc(false); } ilg.Call(ToXXX); } } private string? MakeUnique(EnumMapping mapping, string name) { string uniqueName = name; EnumMapping? m; if (Enums.TryGetValue(uniqueName, out m)) { if (m == mapping) { // we already have created the hashtable return null; } int i = 0; while (m != null) { i++; uniqueName = name + i.ToString(CultureInfo.InvariantCulture); Enums.TryGetValue(uniqueName, out m); } } Enums.Add(uniqueName, mapping); return uniqueName; } [RequiresUnreferencedCode("calls LoadMember")] private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBuilder? get_TableName) { get_TableName = null; CodeIdentifier.CheckValidIdentifier(typeName); string? propName = MakeUnique(mapping, $"{typeName}Values"); if (propName == null) return CodeIdentifier.GetCSharpName(typeName); string memberName = MakeUnique(mapping, $"_{propName}")!; propName = CodeIdentifier.GetCSharpName(propName); FieldBuilder fieldBuilder = this.typeBuilder.DefineField( memberName, typeof(Hashtable), FieldAttributes.Private ); PropertyBuilder propertyBuilder = this.typeBuilder.DefineProperty( propName, PropertyAttributes.None, CallingConventions.HasThis, typeof(Hashtable), null, null, null, null, null); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(Hashtable), $"get_{propName}", Type.EmptyTypes, Array.Empty<string>(), MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.SpecialName); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); ilg.If(Cmp.EqualTo); ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; LocalBuilder hLoc = ilg.DeclareLocal(typeof(Hashtable), "h"); ilg.New(Hashtable_ctor); ilg.Stloc(hLoc); ConstantMapping[] constants = mapping.Constants!; MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } )!; for (int i = 0; i < constants.Length; i++) { ilg.Ldloc(hLoc); ilg.Ldstr(GetCSharpString(constants[i].XmlName)); ilg.Ldc(Enum.ToObject(mapping.TypeDesc!.Type!, constants[i].Value)); ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long)); ilg.ConvertValue(typeof(long), typeof(object)); ilg.Call(Hashtable_Add); } ilg.Ldarg(0); ilg.Ldloc(hLoc); ilg.StoreMember(fieldBuilder); ilg.EndIf(); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); get_TableName = ilg.EndMethod(); propertyBuilder.SetGetMethod(get_TableName!); return propName; } [RequiresUnreferencedCode("calls WriteHashtable")] private void WriteEnumMethod(EnumMapping mapping) { MethodBuilder? get_TableName = null; if (mapping.IsFlags) WriteHashtable(mapping, mapping.TypeDesc!.Name, out get_TableName); string? methodName; MethodNames.TryGetValue(mapping, out methodName); string fullTypeName = mapping.TypeDesc!.CSharpName; List<Type> argTypes = new List<Type>(); List<string> argNames = new List<string>(); Type returnType; Type underlyingType; returnType = mapping.TypeDesc.Type!; underlyingType = Enum.GetUnderlyingType(returnType); argTypes.Add(typeof(string)); argNames.Add("s"); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( returnType, GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); ConstantMapping[] constants = mapping.Constants!; if (mapping.IsFlags) { { MethodInfo XmlSerializationReader_ToEnum = typeof(XmlSerializationReader).GetMethod( "ToEnum", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(Hashtable), typeof(string) } )!; ilg.Ldarg("s"); ilg.Ldarg(0); Debug.Assert(get_TableName != null); ilg.Call(get_TableName); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_ToEnum); // XmlSerializationReader_ToEnum return long! if (underlyingType != typeof(long)) { ilg.ConvertValue(typeof(long), underlyingType); } ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } } else { List<Label> caseLabels = new List<Label>(); List<object> retValues = new List<object>(); Label defaultLabel = ilg.DefineLabel(); Label endSwitchLabel = ilg.DefineLabel(); // This local is necessary; otherwise, it becomes if/else LocalBuilder localTmp = ilg.GetTempLocal(typeof(string)); ilg.Ldarg("s"); ilg.Stloc(localTmp); ilg.Ldloc(localTmp); ilg.Brfalse(defaultLabel); var cases = new HashSet<string>(); for (int i = 0; i < constants.Length; i++) { ConstantMapping c = constants[i]; CodeIdentifier.CheckValidIdentifier(c.Name); if (cases.Add(c.XmlName)) { Label caseLabel = ilg.DefineLabel(); ilg.Ldloc(localTmp); ilg.Ldstr(GetCSharpString(c.XmlName)); MethodInfo String_op_Equality = typeof(string).GetMethod( "op_Equality", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Call(String_op_Equality); ilg.Brtrue(caseLabel); caseLabels.Add(caseLabel); retValues.Add(Enum.ToObject(mapping.TypeDesc.Type!, c.Value)); } } ilg.Br(defaultLabel); // Case bodies for (int i = 0; i < caseLabels.Count; i++) { ilg.MarkLabel(caseLabels[i]); ilg.Ldc(retValues[i]); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } MethodInfo XmlSerializationReader_CreateUnknownConstantException = typeof(XmlSerializationReader).GetMethod( "CreateUnknownConstantException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(Type) } )!; // Default body ilg.MarkLabel(defaultLabel); ilg.Ldarg(0); ilg.Ldarg("s"); // typeof(..) ilg.Ldc(mapping.TypeDesc.Type!); ilg.Call(XmlSerializationReader_CreateUnknownConstantException); ilg.Throw(); // End switch ilg.MarkLabel(endSwitchLabel); } ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls WriteQNameEqual")] private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string returnTypeName) { for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { ilg.InitElseIf(); WriteQNameEqual("xsiType", derived.TypeName, derived.Namespace); ilg.AndIf(); string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc!.Name)); #endif List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); if (derived.TypeDesc!.IsNullable) { ilg.Ldarg("isNullable"); argTypes.Add(typeof(bool)); } ilg.Ldc(false); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, derived.TypeDesc.Type, argTypes.ToArray() ); ilg.Call(methodBuilder); ilg.ConvertValue(methodBuilder.ReturnType, ilg.ReturnLocal.LocalType); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); WriteDerivedTypes(derived, isTypedReturn, returnTypeName); } } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteEnumAndArrayTypes() { foreach (TypeScope scope in Scopes) { foreach (Mapping m in scope.TypeMappings) { if (m is EnumMapping) { EnumMapping mapping = (EnumMapping)m; ilg.InitElseIf(); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); ilg.AndIf(); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif LocalBuilder eLoc = ilg.DeclareOrGetLocal(typeof(object), "e"); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); ilg.Call(XmlSerializationReader_CollapseWhitespace); ilg.Call(methodBuilder); ilg.ConvertValue(methodBuilder.ReturnType, eLoc.LocalType); ilg.Stloc(eLoc); MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.Ldloc(eLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); // Caller own calling ilg.EndIf(); } else if (m is ArrayMapping) { ArrayMapping mapping = (ArrayMapping)m; if (mapping.TypeDesc!.HasDefaultConstructor) { ilg.InitElseIf(); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); ilg.AndIf(); ilg.EnterScope(); MemberMapping memberMapping = new MemberMapping(); memberMapping.TypeDesc = mapping.TypeDesc; memberMapping.Elements = mapping.Elements; string aVar = "a"; string zVar = "z"; Member member = new Member(this, aVar, zVar, 0, memberMapping); TypeDesc td = mapping.TypeDesc; LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type!, aVar); if (mapping.TypeDesc.IsValueType) { RaCodeGen.ILGenForCreateInstance(ilg, td.Type!, false, false); } else ilg.Load(null); ilg.Stloc(aLoc); WriteArray(member.Source, member.ArrayName, mapping, false, false, -1, 0); ilg.Ldloc(aLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.ExitScope(); // Caller own calling ilg.EndIf(); } } } } } [RequiresUnreferencedCode("calls WriteElement")] private void WriteNullableMethod(NullableMapping nullableMapping) { string? methodName; MethodNames.TryGetValue(nullableMapping, out methodName); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( nullableMapping.TypeDesc!.Type!, GetMethodBuilder(methodName!), new Type[] { typeof(bool) }, new string[] { "checkType" }, CodeGenerator.PrivateMethodAttributes); LocalBuilder oLoc = ilg.DeclareLocal(nullableMapping.TypeDesc.Type!, "o"); ilg.LoadAddress(oLoc); ilg.InitObj(nullableMapping.TypeDesc.Type!); MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes)!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); { ilg.Ldloc(oLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); ElementAccessor element = new ElementAccessor(); element.Mapping = nullableMapping.BaseMapping; element.Any = false; element.IsNullable = nullableMapping.BaseMapping!.TypeDesc!.IsNullable; WriteElement("o", null, null, element, null, null, false, false, -1, -1); ilg.Ldloc(oLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls WriteLiteralStructMethod")] private void WriteStructMethod(StructMapping structMapping) { WriteLiteralStructMethod(structMapping); } [RequiresUnreferencedCode("calls WriteEnumAndArrayTypes")] private void WriteLiteralStructMethod(StructMapping structMapping) { string? methodName; MethodNames.TryGetValue(structMapping, out methodName); string typeName = structMapping.TypeDesc!.CSharpName; ilg = new CodeGenerator(this.typeBuilder); List<Type> argTypes = new List<Type>(); List<string> argNames = new List<string>(); if (structMapping.TypeDesc.IsNullable) { argTypes.Add(typeof(bool)); argNames.Add("isNullable"); } argTypes.Add(typeof(bool)); argNames.Add("checkType"); ilg.BeginMethod( structMapping.TypeDesc.Type!, GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); LocalBuilder locXsiType = ilg.DeclareLocal(typeof(XmlQualifiedName), "xsiType"); LocalBuilder locIsNull = ilg.DeclareLocal(typeof(bool), "isNull"); MethodInfo XmlSerializationReader_GetXsiType = typeof(XmlSerializationReader).GetMethod( "GetXsiType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg("checkType"); ilg.Brtrue(labelTrue); ilg.Load(null); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_GetXsiType); ilg.MarkLabel(labelEnd); ilg.Stloc(locXsiType); ilg.Ldc(false); ilg.Stloc(locIsNull); if (structMapping.TypeDesc.IsNullable) { ilg.Ldarg("isNullable"); ilg.If(); { ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.Stloc(locIsNull); } ilg.EndIf(); } ilg.Ldarg("checkType"); ilg.If(); // if (checkType) if (structMapping.TypeDesc.IsRoot) { ilg.Ldloc(locIsNull); ilg.If(); ilg.Ldloc(locXsiType); ilg.Load(null); ilg.If(Cmp.NotEqualTo); MethodInfo XmlSerializationReader_ReadTypedNull = typeof(XmlSerializationReader).GetMethod( "ReadTypedNull", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedNull); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.Else(); if (structMapping.TypeDesc.IsValueType) { throw Globals.NotSupported(SR.Arg_NeverValueType); } else { ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); // if (xsiType != null) ilg.EndIf(); // if (isNull) } ilg.Ldloc(typeof(XmlQualifiedName), "xsiType"); ilg.Load(null); ilg.Ceq(); if (!structMapping.TypeDesc.IsRoot) { labelTrue = ilg.DefineLabel(); labelEnd = ilg.DefineLabel(); // xsiType == null ilg.Brtrue(labelTrue); WriteQNameEqual("xsiType", structMapping.TypeName, structMapping.Namespace); // Bool result for WriteQNameEqual is on the stack ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); } ilg.If(); // if (xsiType == null if (structMapping.TypeDesc.IsRoot) { ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; MethodInfo XmlSerializationReader_ReadTypedPrimitive = typeof(XmlSerializationReader).GetMethod( "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } )!; ilg.Ldarg(0); ilg.Ldstr(Soap.UrType); ilg.Ldstr(XmlSchema.Namespace); ilg.New(XmlQualifiedName_ctor); ilg.Call(XmlSerializationReader_ReadTypedPrimitive); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } WriteDerivedTypes(structMapping, !structMapping.TypeDesc.IsRoot, typeName); if (structMapping.TypeDesc.IsRoot) WriteEnumAndArrayTypes(); ilg.Else(); // if (xsiType == null if (structMapping.TypeDesc.IsRoot) { MethodInfo XmlSerializationReader_ReadTypedPrimitive = typeof(XmlSerializationReader).GetMethod( "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedPrimitive); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } else { MethodInfo XmlSerializationReader_CreateUnknownTypeException = typeof(XmlSerializationReader).GetMethod( "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_CreateUnknownTypeException); ilg.Throw(); } ilg.EndIf(); // if (xsiType == null ilg.EndIf(); // checkType if (structMapping.TypeDesc.IsNullable) { ilg.Ldloc(typeof(bool), "isNull"); ilg.If(); { ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); } if (structMapping.TypeDesc.IsAbstract) { MethodInfo XmlSerializationReader_CreateAbstractTypeException = typeof(XmlSerializationReader).GetMethod( "CreateAbstractTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(structMapping.TypeName)); ilg.Ldstr(GetCSharpString(structMapping.Namespace)); ilg.Call(XmlSerializationReader_CreateAbstractTypeException); ilg.Throw(); } else { if (structMapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(structMapping.TypeDesc.Type)) { MethodInfo XmlSerializationReader_set_DecodeName = typeof(XmlSerializationReader).GetMethod( "set_DecodeName", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_DecodeName); } WriteCreateMapping(structMapping, "o"); LocalBuilder oLoc = ilg.GetLocal("o"); // this method populates the memberInfos dictionary based on the structMapping MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping, memberInfos); Member? anyText = null; Member? anyElement = null; Member? anyAttribute = null; bool isSequence = structMapping.HasExplicitSequence(); var arraysToDeclareList = new List<Member>(mappings.Length); var arraysToSetList = new List<Member>(mappings.Length); var allMembersList = new List<Member>(mappings.Length); for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; CodeIdentifier.CheckValidIdentifier(mapping.Name); string source = RaCodeGen.GetStringForMember("o", mapping.Name, structMapping.TypeDesc); Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) member.ParamsReadSource = $"paramsRead[{i}]"; member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", $"{mapping.Name}Specified", structMapping.TypeDesc); if (mapping.Text != null) anyText = member; if (mapping.Attribute != null && mapping.Attribute.Any) anyAttribute = member; if (!isSequence) { // find anyElement if present. for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { anyElement = member; break; } } } else if (mapping.IsParticle && !mapping.IsSequence) { StructMapping? declaringMapping; structMapping.FindDeclaringMapping(mapping, out declaringMapping, structMapping.TypeName); throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } if (mapping.Attribute == null && mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) { Member arrayMember = new Member(this, source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); arrayMember.CheckSpecifiedSource = member.CheckSpecifiedSource; allMembersList.Add(arrayMember); } else { allMembersList.Add(member); } if (mapping.TypeDesc.IsArrayLike) { arraysToDeclareList.Add(member); if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.ParamsReadSource = null; // flat arrays -- don't want to count params read. if (member != anyText && member != anyElement) { arraysToSetList.Add(member); } } else if (!mapping.TypeDesc.IsArray) { member.ParamsReadSource = null; // collection } } } if (anyElement != null) arraysToSetList.Add(anyElement); if (anyText != null && anyText != anyElement) arraysToSetList.Add(anyText); Member[] arraysToDeclare = arraysToDeclareList.ToArray(); Member[] arraysToSet = arraysToSetList.ToArray(); Member[] allMembers = allMembersList.ToArray(); WriteMemberBegin(arraysToDeclare); WriteParamsRead(mappings.Length); WriteAttributes(allMembers, anyAttribute, "UnknownNode", oLoc); if (anyAttribute != null) WriteMemberEnd(arraysToDeclare); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToElement = typeof(XmlReader).GetMethod( "MoveToElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); ilg.Pop(); MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); WriteMemberEnd(arraysToSet); ilg.Ldloc(oLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.EndIf(); MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); if (IsSequence(allMembers)) { ilg.Ldc(0); ilg.Stloc(typeof(int), "state"); } WriteWhileNotLoopStart(); string unknownNode = $"UnknownNode((object)o, {ExpectedElements(allMembers)});"; WriteMemberElements(allMembers, unknownNode, unknownNode, anyElement, anyText); MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); WriteMemberEnd(arraysToSet); MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.Ldloc(structMapping.TypeDesc.Type!, "o"); ilg.Stloc(ilg.ReturnLocal); } ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } [RequiresUnreferencedCode("calls LoadMember")] private void WriteQNameEqual(string source, string? name, string? ns) { WriteID(name); WriteID(ns); // This api assume the source is local member of XmlQualifiedName type // It leaves bool result on the stack MethodInfo XmlQualifiedName_get_Name = typeof(XmlQualifiedName).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlQualifiedName_get_Namespace = typeof(XmlQualifiedName).GetMethod( "get_Namespace", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelEnd = ilg.DefineLabel(); Label labelFalse = ilg.DefineLabel(); LocalBuilder sLoc = ilg.GetLocal(source); ilg.Ldloc(sLoc); ilg.Call(XmlQualifiedName_get_Name); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[name ?? string.Empty]); ilg.Bne(labelFalse); ilg.Ldloc(sLoc); ilg.Call(XmlQualifiedName_get_Namespace); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[ns ?? string.Empty]); ilg.Ceq(); ilg.Br_S(labelEnd); ilg.MarkLabel(labelFalse); ilg.Ldc(false); ilg.MarkLabel(labelEnd); } [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WriteXmlNodeEqual(string source, string name, string? ns) { WriteXmlNodeEqual(source, name, ns, true); } [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WriteXmlNodeEqual(string source, string name, string? ns, bool doAndIf) { bool isNameNullOrEmpty = string.IsNullOrEmpty(name); if (!isNameNullOrEmpty) { WriteID(name); } WriteID(ns); // Only support Reader and XmlSerializationReaderReader only System.Diagnostics.Debug.Assert(source == "Reader"); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( $"get_{source}", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NamespaceURI = typeof(XmlReader).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); if (!isNameNullOrEmpty) { ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_LocalName); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[name ?? string.Empty]); ilg.Bne(labelFalse); } ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NamespaceURI); ilg.Ldarg(0); ilg.LoadMember(_idNameFields[ns ?? string.Empty]); ilg.Ceq(); if (!isNameNullOrEmpty) { ilg.Br_S(labelEnd); ilg.MarkLabel(labelFalse); ilg.Ldc(false); ilg.MarkLabel(labelEnd); } if (doAndIf) ilg.AndIf(); } private void WriteID(string? name) { if (name == null) { //Writer.Write("null"); //return; name = ""; } if (!_idNames.ContainsKey(name)) { string? idName = NextIdName(name); _idNames.Add(name, idName); _idNameFields.Add(name, this.typeBuilder.DefineField(idName, typeof(string), FieldAttributes.Private)); } } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteAttributes(Member[] members, Member? anyAttribute, string elseCall, LocalBuilder firstParam) { int count = 0; Member? xmlnsMember = null; var attributes = new List<AttributeAccessor>(); // Condition do at the end, so C# looks the same MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToNextAttribute = typeof(XmlReader).GetMethod( "MoveToNextAttribute", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.WhileBegin(); for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.Mapping.Xmlns != null) { xmlnsMember = member; continue; } if (member.Mapping.Ignore) continue; AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; attributes.Add(attribute); if (count++ > 0) ilg.InitElseIf(); else ilg.InitIf(); if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource); ilg.Ldc(false); ilg.AndIf(Cmp.EqualTo); } if (attribute.IsSpecialXmlNamespace) { WriteXmlNodeEqual("Reader", attribute.Name, XmlReservedNs.NsXml); } else WriteXmlNodeEqual("Reader", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : ""); WriteAttribute(member); } if (count > 0) ilg.InitElseIf(); else ilg.InitIf(); if (xmlnsMember != null) { MethodInfo XmlSerializationReader_IsXmlnsAttribute = typeof(XmlSerializationReader).GetMethod( "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Name); ilg.Call(XmlSerializationReader_IsXmlnsAttribute); ilg.Ldc(true); ilg.AndIf(Cmp.EqualTo); ILGenLoad(xmlnsMember.Source); ilg.Load(null); ilg.If(Cmp.EqualTo); WriteSourceBegin(xmlnsMember.Source); ConstructorInfo ctor = xmlnsMember.Mapping.TypeDesc!.Type!.GetConstructor( CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.New(ctor); WriteSourceEnd(xmlnsMember.Source, xmlnsMember.Mapping.TypeDesc.Type!); ilg.EndIf(); // if (xmlnsMember.Source == null Label labelEqual5 = ilg.DefineLabel(); Label labelEndLength = ilg.DefineLabel(); MethodInfo Add = xmlnsMember.Mapping.TypeDesc.Type!.GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } )!; MethodInfo String_get_Length = typeof(string).GetMethod( "get_Length", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ILGenLoad(xmlnsMember.ArraySource, xmlnsMember.Mapping.TypeDesc.Type); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Name); ilg.Call(String_get_Length); ilg.Ldc(5); ilg.Beq(labelEqual5); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_LocalName); ilg.Br(labelEndLength); ilg.MarkLabel(labelEqual5); ilg.Ldstr(string.Empty); ilg.MarkLabel(labelEndLength); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); ilg.Call(Add); ilg.Else(); } else { MethodInfo XmlSerializationReader_IsXmlnsAttribute = typeof(XmlSerializationReader).GetMethod( "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Name); ilg.Call(XmlSerializationReader_IsXmlnsAttribute); ilg.Ldc(false); ilg.AndIf(Cmp.EqualTo); } if (anyAttribute != null) { LocalBuilder localAttr = ilg.DeclareOrGetLocal(typeof(XmlAttribute), "attr"); MethodInfo XmlSerializationReader_get_Document = typeof(XmlSerializationReader).GetMethod( "get_Document", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlDocument_ReadNode = typeof(XmlDocument).GetMethod( "ReadNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlReader) } )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlDocument_ReadNode); ilg.ConvertValue(XmlDocument_ReadNode.ReturnType, localAttr.LocalType); ilg.Stloc(localAttr); MethodInfo XmlSerializationReader_ParseWsdlArrayType = typeof(XmlSerializationReader).GetMethod( "ParseWsdlArrayType", CodeGenerator.InstanceBindingFlags, new Type[] { localAttr.LocalType } )!; ilg.Ldarg(0); ilg.Ldloc(localAttr); ilg.Call(XmlSerializationReader_ParseWsdlArrayType); WriteAttribute(anyAttribute); } else { List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); argTypes.Add(typeof(object)); ilg.Ldloc(firstParam); ilg.ConvertValue(firstParam.LocalType, typeof(object)); if (attributes.Count > 0) { string qnames = ""; for (int i = 0; i < attributes.Count; i++) { AttributeAccessor attribute = attributes[i]; if (i > 0) qnames += ", "; qnames += attribute.IsSpecialXmlNamespace ? XmlReservedNs.NsXml : $"{(attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "")}:{attribute.Name}"; } argTypes.Add(typeof(string)); ilg.Ldstr(qnames); } System.Diagnostics.Debug.Assert(elseCall == "UnknownNode"); MethodInfo elseCallMethod = typeof(XmlSerializationReader).GetMethod( elseCall, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() )!; ilg.Call(elseCallMethod); } ilg.EndIf(); ilg.WhileBeginCondition(); { ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToNextAttribute); } ilg.WhileEndCondition(); ilg.WhileEnd(); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteAttribute(Member member) { AttributeAccessor attribute = member.Mapping.Attribute!; if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); ilg.Ldloc("attr"); WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } else if (special.TypeDesc.CanBeAttributeValue) { LocalBuilder attrLoc = ilg.GetLocal("attr"); ilg.Ldloc(attrLoc); // to get code compat if (attrLoc.LocalType == typeof(XmlAttribute)) { ilg.Load(null); ilg.Cne(); } else ilg.IsInst(typeof(XmlAttribute)); ilg.If(); WriteSourceBegin(member.ArraySource); ilg.Ldloc(attrLoc); ilg.ConvertValue(attrLoc.LocalType, typeof(XmlAttribute)); WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); ilg.EndIf(); } else throw new InvalidOperationException(SR.XmlInternalError); } else { if (attribute.IsList) { LocalBuilder locListValues = ilg.DeclareOrGetLocal(typeof(string), "listValues"); LocalBuilder locVals = ilg.DeclareOrGetLocal(typeof(string[]), "vals"); MethodInfo String_Split = typeof(string).GetMethod( "Split", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(char[]) } )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); ilg.Stloc(locListValues); ilg.Ldloc(locListValues); ilg.Load(null); ilg.Call(String_Split); ilg.Stloc(locVals); LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), "i"); ilg.For(localI, 0, locVals); string attributeSource = GetArraySource(member.Mapping.TypeDesc!, member.ArrayName); WriteSourceBegin(attributeSource); WritePrimitive(attribute.Mapping!, "vals[i]"); WriteSourceEnd(attributeSource, member.Mapping.TypeDesc!.ArrayElementTypeDesc!.Type!); ilg.EndFor(); } else { WriteSourceBegin(member.ArraySource); WritePrimitive(attribute.Mapping!, attribute.IsList ? "vals[i]" : "Reader.Value"); WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } } if (member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite && member.CheckSpecifiedSource != null && member.CheckSpecifiedSource.Length > 0) { ILGenSet(member.CheckSpecifiedSource, true); } if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource, true); } } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteMemberBegin(Member[] members) { for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.IsArrayLike) { string a = member.ArrayName; string c = $"c{a}"; TypeDesc typeDesc = member.Mapping.TypeDesc!; if (member.Mapping.TypeDesc!.IsArray) { WriteArrayLocalDecl(typeDesc.CSharpName, a, "null", typeDesc); ilg.Ldc(0); ilg.Stloc(typeof(int), c); if (member.Mapping.ChoiceIdentifier != null) { WriteArrayLocalDecl($"{member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName}[]", member.ChoiceArrayName, "null", member.Mapping.ChoiceIdentifier.Mapping.TypeDesc); ilg.Ldc(0); ilg.Stloc(typeof(int), $"c{member.ChoiceArrayName}"); } } else { if (member.Source[member.Source.Length - 1] == '(' || member.Source[member.Source.Length - 1] == '{') { WriteCreateInstance(a, typeDesc.CannotNew, typeDesc.Type!); WriteSourceBegin(member.Source); ilg.Ldloc(ilg.GetLocal(a)); WriteSourceEnd(member.Source, typeDesc.Type!); } else { if (member.IsList && !member.Mapping.ReadOnly && member.Mapping.TypeDesc.IsNullable) { // we need to new the Collections and ArrayLists ILGenLoad(member.Source, typeof(object)); ilg.Load(null); ilg.If(Cmp.EqualTo); if (!member.Mapping.TypeDesc.HasDefaultConstructor) { MethodInfo XmlSerializationReader_CreateReadOnlyCollectionException = typeof(XmlSerializationReader).GetMethod( "CreateReadOnlyCollectionException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(member.Mapping.TypeDesc.CSharpName)); ilg.Call(XmlSerializationReader_CreateReadOnlyCollectionException); ilg.Throw(); } else { WriteSourceBegin(member.Source); RaCodeGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type!, typeDesc.CannotNew, true); WriteSourceEnd(member.Source, member.Mapping.TypeDesc.Type!); } ilg.EndIf(); // if ((object)(member.Source) == null } WriteLocalDecl(a, new SourceInfo(member.Source, member.Source, member.Mapping.MemberInfo, member.Mapping.TypeDesc.Type, ilg)); } } } } } private string ExpectedElements(Member[] members) { if (IsSequence(members)) return "null"; string qnames = string.Empty; bool firstElement = true; for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.Mapping.Xmlns != null) continue; if (member.Mapping.Ignore) continue; if (member.Mapping.IsText || member.Mapping.IsAttribute) continue; ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement) qnames += ", "; qnames += $"{ns}:{e.Name}"; firstElement = false; } } return ReflectionAwareILGen.GetQuotedCSharpString(qnames); } [RequiresUnreferencedCode("calls WriteMemberElementsIf")] private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member? anyElement, Member? anyText) { if (anyText != null) { ilg.Load(null); ilg.Stloc(typeof(string), "tmp"); } MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; int XmlNodeType_Element = 1; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType_Element); ilg.If(Cmp.EqualTo); WriteMemberElementsIf(members, anyElement, elementElseString); if (anyText != null) WriteMemberText(anyText, elseString); ilg.Else(); ILGenElseString(elseString); ilg.EndIf(); } [RequiresUnreferencedCode("calls WriteText")] private void WriteMemberText(Member anyText, string elseString) { ilg.InitElseIf(); Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.Text); ilg.Ceq(); ilg.Brtrue(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.CDATA); ilg.Ceq(); ilg.Brtrue(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.Whitespace); ilg.Ceq(); ilg.Brtrue(labelTrue); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType.SignificantWhitespace); ilg.Ceq(); ilg.Br(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); ilg.AndIf(); if (anyText != null) { WriteText(anyText); } Debug.Assert(anyText != null); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteText(Member member) { TextAccessor text = member.Mapping.Text!; if (text.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); switch (special.TypeDesc!.Kind) { case TypeKind.Node: MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlSerializationReader_get_Document = typeof(XmlSerializationReader).GetMethod( "get_Document", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlDocument_CreateTextNode = typeof(XmlDocument).GetMethod( "CreateTextNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); ilg.Call(XmlDocument_CreateTextNode); break; default: throw new InvalidOperationException(SR.XmlInternalError); } WriteSourceEnd(member.ArraySource, special.TypeDesc.Type!); } else { if (member.IsArrayLike) { WriteSourceBegin(member.ArraySource); if (text.Mapping!.TypeDesc!.CollapseWhitespace) { ilg.Ldarg(0); // for calling CollapseWhitespace } else { } MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); if (text.Mapping.TypeDesc.CollapseWhitespace) { MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } else { if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { LocalBuilder tmpLoc = ilg.GetLocal("tmp"); MethodInfo XmlSerializationReader_ReadString = typeof(XmlSerializationReader).GetMethod( "ReadString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldloc(tmpLoc); ilg.Ldc(text.Mapping.TypeDesc!.CollapseWhitespace); ilg.Call(XmlSerializationReader_ReadString); ilg.Stloc(tmpLoc); WriteSourceBegin(member.ArraySource); ilg.Ldloc(tmpLoc); } else { WriteSourceBegin(member.ArraySource); WritePrimitive(text.Mapping, "Reader.ReadString()"); } } WriteSourceEnd(member.ArraySource, text.Mapping.TypeDesc.Type!); } } [RequiresUnreferencedCode("calls WriteElement")] private void WriteMemberElementsElse(Member? anyElement, string elementElseString) { if (anyElement != null) { ElementAccessor[] elements = anyElement.Mapping.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; if (element.Any && element.Name.Length == 0) { WriteElement(anyElement.ArraySource, anyElement.ArrayName, anyElement.ChoiceArraySource, element, anyElement.Mapping.ChoiceIdentifier, anyElement.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? anyElement.CheckSpecifiedSource : null, false, false, -1, i); break; } } } else { ILGenElementElseString(elementElseString); } } private bool IsSequence(Member[] members) { for (int i = 0; i < members.Length; i++) { if (members[i].Mapping.IsParticle && members[i].Mapping.IsSequence) return true; } return false; } [RequiresUnreferencedCode("calls WriteElement")] private void WriteMemberElementsIf(Member[] members, Member? anyElement, string elementElseString) { int count = 0; bool isSequence = IsSequence(members); int cases = 0; for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.Mapping.Xmlns != null) continue; if (member.Mapping.Ignore) continue; if (isSequence && (member.Mapping.IsText || member.Mapping.IsAttribute)) continue; bool firstElement = true; ChoiceIdentifierAccessor? choice = member.Mapping.ChoiceIdentifier; ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement || (!isSequence && count > 0)) { ilg.InitElseIf(); } else if (isSequence) { if (cases > 0) ilg.InitElseIf(); else ilg.InitIf(); ilg.Ldloc("state"); ilg.Ldc(cases); ilg.AndIf(Cmp.EqualTo); ilg.InitIf(); } else { ilg.InitIf(); } count++; firstElement = false; if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource); ilg.Ldc(false); ilg.AndIf(Cmp.EqualTo); } Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); if (member.Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_get_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "get_IsReturnValue", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_IsReturnValue); ilg.Brtrue(labelTrue); } if (isSequence && e.Any && e.AnyNamespaces == null) { ilg.Ldc(true); } else { WriteXmlNodeEqual("Reader", e.Name, ns, false); } if (member.Mapping.IsReturnValue) { ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); } ilg.AndIf(); WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc!.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); if (member.Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_IsReturnValue); } if (member.ParamsReadSource != null) { ILGenParamsReadSource(member.ParamsReadSource, true); } } if (isSequence) { if (member.IsArrayLike) { ilg.Else(); } else { ilg.EndIf(); } cases++; ilg.Ldc(cases); ilg.Stloc(ilg.GetLocal("state")); if (member.IsArrayLike) { ilg.EndIf(); } } } if (count > 0) { ilg.Else(); } WriteMemberElementsElse(anyElement, elementElseString); if (count > 0) { ilg.EndIf(); } } private string GetArraySource(TypeDesc typeDesc, string arrayName) { return GetArraySource(typeDesc, arrayName, false); } private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef) { string a = arrayName; string c = $"c{a}"; string init = ""; if (multiRef) { init = $"soap = (System.Object[])EnsureArrayIndex(soap, {c}+2, typeof(System.Object)); "; } if (typeDesc.IsArray) { string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; init = $"{init}{a} = ({arrayTypeFullName}[])EnsureArrayIndex({a}, {c}, {RaCodeGen.GetStringForTypeof(arrayTypeFullName)});"; string arraySource = RaCodeGen.GetStringForArrayMember(a, $"{c}++", typeDesc); if (multiRef) { init = $"{init} soap[1] = {a};"; init = $"{init} if (ReadReference(out soap[{c}+2])) {arraySource} = null; else "; } return $"{init}{arraySource}"; } else { return RaCodeGen.GetStringForMethod(arrayName, typeDesc.CSharpName, "Add"); } } [RequiresUnreferencedCode("calls WriteMemberEnd")] private void WriteMemberEnd(Member[] members) { WriteMemberEnd(members, false); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteMemberEnd(Member[] members, bool soapRefs) { for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; if (member.IsArrayLike) { TypeDesc typeDesc = member.Mapping.TypeDesc!; if (typeDesc.IsArray) { WriteSourceBegin(member.Source); Debug.Assert(!soapRefs); string a = member.ArrayName; string c = $"c{a}"; MethodInfo XmlSerializationReader_ShrinkArray = typeof(XmlSerializationReader).GetMethod( "ShrinkArray", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type), typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); ilg.Ldc(typeDesc.ArrayElementTypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, typeDesc.Type!); WriteSourceEnd(member.Source, typeDesc.Type!); if (member.Mapping.ChoiceIdentifier != null) { WriteSourceBegin(member.ChoiceSource!); a = member.ChoiceArrayName; c = $"c{a}"; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); ilg.Ldc(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); WriteSourceEnd(member.ChoiceSource!, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); } } else if (typeDesc.IsValueType) { LocalBuilder arrayLoc = ilg.GetLocal(member.ArrayName); WriteSourceBegin(member.Source); ilg.Ldloc(arrayLoc); WriteSourceEnd(member.Source, arrayLoc.LocalType); } } } } private void WriteSourceBeginTyped(string source, TypeDesc? typeDesc) { WriteSourceBegin(source); } [RegexGenerator("(?<locA1>[^ ]+) = .+EnsureArrayIndex[(](?<locA2>[^,]+), (?<locI1>[^,]+),[^;]+;(?<locA3>[^[]+)[[](?<locI2>[^+]+)[+][+][]]")] private static partial Regex EnsureArrayIndexRegex(); [RegexGenerator("(?<a>[^[]+)[[](?<ia>.+)[]]")] private static partial Regex P0Regex(); private void WriteSourceBegin(string source) { object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { // local address to invoke ctor on WriteSourceEnd ilg.LoadAddress(variable); } return; } // o.@Field if (source.StartsWith("o.@", StringComparison.Ordinal)) { ilg.LdlocAddress(ilg.GetLocal("o")); return; } // a_0_0 = (global::System.Object[])EnsureArrayIndex(a_0_0, ca_0_0, typeof(global::System.Object));a_0_0[ca_0_0++] Match match = EnsureArrayIndexRegex().Match(source); if (match.Success) { Debug.Assert(match.Groups["locA1"].Value == match.Groups["locA2"].Value); Debug.Assert(match.Groups["locA1"].Value == match.Groups["locA3"].Value); Debug.Assert(match.Groups["locI1"].Value == match.Groups["locI2"].Value); LocalBuilder localA = ilg.GetLocal(match.Groups["locA1"].Value); LocalBuilder localI = ilg.GetLocal(match.Groups["locI1"].Value); Type arrayElementType = localA.LocalType.GetElementType()!; MethodInfo XmlSerializationReader_EnsureArrayIndex = typeof(XmlSerializationReader).GetMethod( "EnsureArrayIndex", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type) } )!; ilg.Ldarg(0); ilg.Ldloc(localA); ilg.Ldloc(localI); ilg.Ldc(arrayElementType); ilg.Call(XmlSerializationReader_EnsureArrayIndex); ilg.Castclass(localA.LocalType); ilg.Stloc(localA); // a_0[ca_0++] ilg.Ldloc(localA); ilg.Ldloc(localI); ilg.Dup(); ilg.Ldc(1); ilg.Add(); ilg.Stloc(localI); if (CodeGenerator.IsNullableGenericType(arrayElementType) || arrayElementType.IsValueType) { ilg.Ldelema(arrayElementType); } return; } //"a_0_0.Add(" if (source.EndsWith(".Add(", StringComparison.Ordinal)) { int index = source.LastIndexOf(".Add(", StringComparison.Ordinal); LocalBuilder localA = ilg.GetLocal(source.Substring(0, index)); ilg.LdlocAddress(localA); return; } // p[0] match = P0Regex().Match(source); if (match.Success) { System.Diagnostics.Debug.Assert(ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)).IsArray); ilg.Load(ilg.GetVariable(match.Groups["a"].Value)); ilg.Load(ilg.GetVariable(match.Groups["ia"].Value)); return; } throw Globals.NotSupported($"Unexpected: {source}"); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void WriteSourceEnd(string source, Type elementType) { WriteSourceEnd(source, elementType, elementType); } [RequiresUnreferencedCode("string-based IL generation")] private void WriteSourceEnd(string source, Type elementType, Type stackType) { object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { ilg.Call(varType.GetConstructor(varType.GetGenericArguments())!); } else { Debug.Assert(elementType != null && variable is LocalBuilder); ilg.ConvertValue(stackType, elementType); ilg.ConvertValue(elementType, varType); ilg.Stloc((LocalBuilder)variable); } return; } // o.@Field if (source.StartsWith("o.@", StringComparison.Ordinal)) { Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); MemberInfo memInfo = memberInfos[source.Substring(3)]; ilg.ConvertValue(stackType, memInfo is FieldInfo ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType); ilg.StoreMember(memInfo); return; } // a_0_0 = (global::System.Object[])EnsureArrayIndex(a_0_0, ca_0_0, typeof(global::System.Object));a_0_0[ca_0_0++] Match match = EnsureArrayIndexRegex().Match(source); if (match.Success) { object oVar = ilg.GetVariable(match.Groups["locA1"].Value); Type arrayElementType = ilg.GetVariableType(oVar).GetElementType()!; ilg.ConvertValue(elementType, arrayElementType); if (CodeGenerator.IsNullableGenericType(arrayElementType) || arrayElementType.IsValueType) { ilg.Stobj(arrayElementType); } else { ilg.Stelem(arrayElementType); } return; } //"a_0_0.Add(" if (source.EndsWith(".Add(", StringComparison.Ordinal)) { int index = source.LastIndexOf(".Add(", StringComparison.Ordinal); LocalBuilder localA = ilg.GetLocal(source.Substring(0, index)); Debug.Assert(!localA.LocalType.IsGenericType || (localA.LocalType.GetGenericArguments().Length == 1 && localA.LocalType.GetGenericArguments()[0].IsAssignableFrom(elementType))); MethodInfo Add = localA.LocalType.GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { elementType } )!; Debug.Assert(Add != null); Type addParameterType = Add.GetParameters()[0].ParameterType; ilg.ConvertValue(stackType, addParameterType); ilg.Call(Add); if (Add.ReturnType != typeof(void)) ilg.Pop(); return; } // p[0] match = P0Regex().Match(source); if (match.Success) { Type varType = ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)); System.Diagnostics.Debug.Assert(varType.IsArray); Type varElementType = varType.GetElementType()!; ilg.ConvertValue(stackType, varElementType); ilg.Stelem(varElementType); return; } throw Globals.NotSupported($"Unexpected: {source}"); } [RequiresUnreferencedCode("calls WriteMemberBegin")] private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex, int elementIndex) { MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.IfNot(); MemberMapping memberMapping = new MemberMapping(); memberMapping.Elements = arrayMapping.Elements; memberMapping.TypeDesc = arrayMapping.TypeDesc; memberMapping.ReadOnly = readOnly; if (source.StartsWith("o.@", StringComparison.Ordinal)) { Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); memberMapping.MemberInfo = memberInfos[source.Substring(3)]; } Member member = new Member(this, source, arrayName, elementIndex, memberMapping, false); member.IsNullable = false; //Note, IsNullable is set to false since null condition (xsi:nil) is already handled by 'ReadNull()' Member[] members = new Member[] { member }; WriteMemberBegin(members); Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); if (readOnly) { ilg.Load(ilg.GetVariable(member.ArrayName)); ilg.Load(null); ilg.Beq(labelTrue); } else { } MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); if (readOnly) { ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); } ilg.If(); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Else(); MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); WriteWhileNotLoopStart(); string unknownNode = $"UnknownNode(null, {ExpectedElements(members)});"; WriteMemberElements(members, unknownNode, unknownNode, null, null); MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); WriteWhileLoopEnd(); MethodInfo XmlSerializationReader_ReadEndElement = typeof(XmlSerializationReader).GetMethod( "ReadEndElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.EndIf(); WriteMemberEnd(members, false); if (isNullable) { ilg.Else(); member.IsNullable = true; WriteMemberBegin(members); WriteMemberEnd(members); } ilg.EndIf(); } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteElement(string source, string? arrayName, string? choiceSource, ElementAccessor element, ChoiceIdentifierAccessor? choice, string? checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) { if (checkSpecified != null && checkSpecified.Length > 0) { ILGenSet(checkSpecified, true); } if (element.Mapping is ArrayMapping) { WriteArray(source, arrayName, (ArrayMapping)element.Mapping, readOnly, element.IsNullable, fixupIndex, elementIndex); } else if (element.Mapping is NullableMapping) { string? methodName = ReferenceMapping(element.Mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc!.Name)); #endif WriteSourceBegin(source); ilg.Ldarg(0); ilg.Ldc(true); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, // See WriteNullableMethod for different return type logic element.Mapping.TypeDesc!.Type, new Type[] { typeof(bool) } ); ilg.Call(methodBuilder); WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } else if (element.Mapping is PrimitiveMapping) { bool doEndIf = false; if (element.IsNullable) { MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); WriteSourceBegin(source); if (element.Mapping.TypeDesc!.IsValueType) { throw Globals.NotSupported("No such condition. PrimitiveMapping && IsNullable = String, XmlQualifiedName and never IsValueType"); } else { ilg.Load(null); } WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); ilg.Else(); doEndIf = true; } if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Else(); doEndIf = true; } else { } if ((element.Mapping.TypeDesc!.Type == typeof(TimeSpan)) || element.Mapping.TypeDesc!.Type == typeof(DateTimeOffset)) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); ilg.If(); WriteSourceBegin(source); MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); LocalBuilder tmpLoc = ilg.GetTempLocal(element.Mapping.TypeDesc!.Type); ilg.Ldloca(tmpLoc); ilg.InitObj(element.Mapping.TypeDesc!.Type); ilg.Ldloc(tmpLoc); WriteSourceEnd(source, element.Mapping.TypeDesc.Type); ilg.Else(); WriteSourceBegin(source); WritePrimitive(element.Mapping, "Reader.ReadElementString()"); WriteSourceEnd(source, element.Mapping.TypeDesc.Type); ilg.EndIf(); } else { WriteSourceBegin(source); if (element.Mapping.TypeDesc == QnameTypeDesc) { MethodInfo XmlSerializationReader_ReadElementQualifiedName = typeof(XmlSerializationReader).GetMethod( "ReadElementQualifiedName", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadElementQualifiedName); } else { string readFunc; switch (element.Mapping.TypeDesc.FormatterName) { case "ByteArrayBase64": case "ByteArrayHex": readFunc = "false"; break; default: readFunc = "Reader.ReadElementString()"; break; } WritePrimitive(element.Mapping, readFunc); } WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } if (doEndIf) ilg.EndIf(); } else if (element.Mapping is StructMapping) { TypeMapping mapping = element.Mapping; string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif if (checkForNull) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldloc(arrayName!); ilg.Load(null); ilg.If(Cmp.EqualTo); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); ilg.Else(); } WriteSourceBegin(source); List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); if (mapping.TypeDesc!.IsNullable) { ilg.Load(element.IsNullable); argTypes.Add(typeof(bool)); } ilg.Ldc(true); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc.Type, argTypes.ToArray() ); ilg.Call(methodBuilder); WriteSourceEnd(source, mapping.TypeDesc.Type!); if (checkForNull) // 'If' begins in checkForNull above ilg.EndIf(); } else if (element.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)element.Mapping; switch (special.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; WriteSourceBeginTyped(source, special.TypeDesc); MethodInfo XmlSerializationReader_ReadXmlXXX = typeof(XmlSerializationReader).GetMethod( isDoc ? "ReadXmlDocument" : "ReadXmlNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } )!; ilg.Ldarg(0); ilg.Ldc(element.Any ? false : true); ilg.Call(XmlSerializationReader_ReadXmlXXX); // See logic in WriteSourceBeginTyped whether or not to castclass. if (special.TypeDesc != null) ilg.Castclass(special.TypeDesc.Type!); WriteSourceEnd(source, special.TypeDesc!.Type!); break; case TypeKind.Serializable: SerializableMapping sm = (SerializableMapping)element.Mapping; // check to see if we need to do the derivation if (sm.DerivedMappings != null) { MethodInfo XmlSerializationReader_GetXsiType = typeof(XmlSerializationReader).GetMethod( "GetXsiType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); LocalBuilder tserLoc = ilg.DeclareOrGetLocal(typeof(XmlQualifiedName), "tser"); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_GetXsiType); ilg.Stloc(tserLoc); ilg.Ldloc(tserLoc); ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); WriteQNameEqual("tser", sm.XsiType!.Name, sm.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); ilg.If(); } WriteSourceBeginTyped(source, sm.TypeDesc!); bool isWrappedAny = !element.Any && IsWildcard(sm); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } )!; ilg.Ldarg(0); RaCodeGen.ILGenForCreateInstance(ilg, sm.TypeDesc!.Type!, sm.TypeDesc.CannotNew, false); if (sm.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) ilg.Ldc(true); ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (sm.TypeDesc != null) ilg.ConvertValue(typeof(IXmlSerializable), sm.TypeDesc.Type!); WriteSourceEnd(source, sm.TypeDesc!.Type!); if (sm.DerivedMappings != null) { WriteDerivedSerializable(sm, sm, source, isWrappedAny); WriteUnknownNode("UnknownNode", "null", null, true); } break; default: throw new InvalidOperationException(SR.XmlInternalError); } } else { throw new InvalidOperationException(SR.XmlInternalError); } if (choice != null) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source)); #endif WriteSourceBegin(choiceSource!); CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping!.TypeDesc!.Type!, choice.MemberIds[elementIndex]); WriteSourceEnd(choiceSource!, choice.Mapping.TypeDesc.Type!); } } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteDerivedSerializable(SerializableMapping head, SerializableMapping? mapping, string source, bool isWrappedAny) { if (mapping == null) return; for (SerializableMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); LocalBuilder tserLoc = ilg.GetLocal("tser"); ilg.InitElseIf(); ilg.Ldloc(tserLoc); ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); WriteQNameEqual("tser", derived.XsiType!.Name, derived.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); ilg.Ldc(true); ilg.MarkLabel(labelEnd); ilg.AndIf(); if (derived.Type != null) { if (head.Type!.IsAssignableFrom(derived.Type)) { WriteSourceBeginTyped(source, head.TypeDesc!); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } )!; ilg.Ldarg(0); RaCodeGen.ILGenForCreateInstance(ilg, derived.TypeDesc!.Type!, derived.TypeDesc.CannotNew, false); if (derived.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) ilg.Ldc(true); ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (head.TypeDesc != null) ilg.ConvertValue(typeof(IXmlSerializable), head.TypeDesc.Type!); WriteSourceEnd(source, head.TypeDesc!.Type!); } else { MethodInfo XmlSerializationReader_CreateBadDerivationException = typeof(XmlSerializationReader).GetMethod( "CreateBadDerivationException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(head.XsiType!.Name)); ilg.Ldstr(GetCSharpString(head.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(derived.Type.FullName)); ilg.Ldstr(GetCSharpString(head.Type.FullName)); ilg.Call(XmlSerializationReader_CreateBadDerivationException); ilg.Throw(); } } else { MethodInfo XmlSerializationReader_CreateMissingIXmlSerializableType = typeof(XmlSerializationReader).GetMethod( "CreateMissingIXmlSerializableType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(head.Type!.FullName)); ilg.Call(XmlSerializationReader_CreateMissingIXmlSerializableType); ilg.Throw(); } WriteDerivedSerializable(head, derived, source, isWrappedAny); } } private void WriteWhileNotLoopStart() { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); ilg.Pop(); ilg.WhileBegin(); } private void WriteWhileLoopEnd() { ilg.WhileBeginCondition(); { int XmlNodeType_None = 0; //int XmlNodeType_Element = 1; int XmlNodeType_EndElement = 15; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType_EndElement); ilg.Beq(labelFalse); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); ilg.Ldc(XmlNodeType_None); ilg.Cne(); ilg.Br_S(labelEnd); ilg.MarkLabel(labelFalse); ilg.Ldc(false); ilg.MarkLabel(labelEnd); } ilg.WhileEndCondition(); ilg.WhileEnd(); } private void WriteParamsRead(int length) { LocalBuilder paramsRead = ilg.DeclareLocal(typeof(bool[]), "paramsRead"); ilg.NewArray(typeof(bool), length); ilg.Stloc(paramsRead); } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] private void WriteCreateMapping(TypeMapping mapping, string local) { string fullTypeName = mapping.TypeDesc!.CSharpName; bool ctorInaccessible = mapping.TypeDesc.CannotNew; LocalBuilder loc = ilg.DeclareLocal( mapping.TypeDesc.Type!, local); if (ctorInaccessible) { ilg.BeginExceptionBlock(); } RaCodeGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type!, mapping.TypeDesc.CannotNew, true); ilg.Stloc(loc); if (ctorInaccessible) { ilg.Leave(); WriteCatchException(typeof(MissingMethodException)); MethodInfo XmlSerializationReader_CreateInaccessibleConstructorException = typeof(XmlSerializationReader).GetMethod( "CreateInaccessibleConstructorException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateInaccessibleConstructorException); ilg.Throw(); WriteCatchException(typeof(SecurityException)); MethodInfo XmlSerializationReader_CreateCtorHasSecurityException = typeof(XmlSerializationReader).GetMethod( "CreateCtorHasSecurityException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateCtorHasSecurityException); ilg.Throw(); ilg.EndExceptionBlock(); } } private void WriteCatchException(Type exceptionType) { ilg.BeginCatchBlock(exceptionType); ilg.Pop(); } [RequiresUnreferencedCode("calls WriteArrayLocalDecl")] private void WriteArrayLocalDecl(string typeName, string variableName, string initValue, TypeDesc arrayTypeDesc) { RaCodeGen.WriteArrayLocalDecl(typeName, variableName, new SourceInfo(initValue, initValue, null, arrayTypeDesc.Type, ilg), arrayTypeDesc); } [RequiresUnreferencedCode("calls WriteCreateInstance")] private void WriteCreateInstance(string source, bool ctorInaccessible, Type type) { RaCodeGen.WriteCreateInstance(source, ctorInaccessible, type, ilg); } [RequiresUnreferencedCode("calls WriteLocalDecl")] private void WriteLocalDecl(string variableName, SourceInfo initValue) { RaCodeGen.WriteLocalDecl(variableName, initValue); } [RegexGenerator("UnknownNode[(]null, @[\"](?<qnames>[^\"]*)[\"][)];")] private static partial Regex UnknownNodeNullAnyTypeRegex(); [RegexGenerator("UnknownNode[(][(]object[)](?<o>[^,]+), @[\"](?<qnames>[^\"]*)[\"][)];")] private static partial Regex UnknownNodeObjectEmptyRegex(); [RegexGenerator("UnknownNode[(][(]object[)](?<o>[^,]+), null[)];")] private static partial Regex UnknownNodeObjectNullRegex(); [RegexGenerator("UnknownNode[(][(]object[)](?<o>[^)]+)[)];")] private static partial Regex UnknownNodeObjectRegex(); [RegexGenerator("paramsRead\\[(?<index>[0-9]+)\\]")] private static partial Regex ParamsReadRegex(); private void ILGenElseString(string elseString) { MethodInfo XmlSerializationReader_UnknownNode1 = typeof(XmlSerializationReader).GetMethod( "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } )!; MethodInfo XmlSerializationReader_UnknownNode2 = typeof(XmlSerializationReader).GetMethod( "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(string) } )!; // UnknownNode(null, @":anyType"); Match match = UnknownNodeNullAnyTypeRegex().Match(elseString); if (match.Success) { ilg.Ldarg(0); ilg.Load(null); ilg.Ldstr(match.Groups["qnames"].Value); ilg.Call(XmlSerializationReader_UnknownNode2); return; } // UnknownNode((object)o, @""); match = UnknownNodeObjectEmptyRegex().Match(elseString); if (match.Success) { ilg.Ldarg(0); LocalBuilder localO = ilg.GetLocal(match.Groups["o"].Value); ilg.Ldloc(localO); ilg.ConvertValue(localO.LocalType, typeof(object)); ilg.Ldstr(match.Groups["qnames"].Value); ilg.Call(XmlSerializationReader_UnknownNode2); return; } // UnknownNode((object)o, null); match = UnknownNodeObjectNullRegex().Match(elseString); if (match.Success) { ilg.Ldarg(0); LocalBuilder localO = ilg.GetLocal(match.Groups["o"].Value); ilg.Ldloc(localO); ilg.ConvertValue(localO.LocalType, typeof(object)); ilg.Load(null); ilg.Call(XmlSerializationReader_UnknownNode2); return; } // "UnknownNode((object)o);" match = UnknownNodeObjectRegex().Match(elseString); if (match.Success) { ilg.Ldarg(0); LocalBuilder localO = ilg.GetLocal(match.Groups["o"].Value); ilg.Ldloc(localO); ilg.ConvertValue(localO.LocalType, typeof(object)); ilg.Call(XmlSerializationReader_UnknownNode1); return; } throw Globals.NotSupported($"Unexpected: {elseString}"); } private void ILGenParamsReadSource(string paramsReadSource) { Match match = ParamsReadRegex().Match(paramsReadSource); if (match.Success) { ilg.LoadArrayElement(ilg.GetLocal("paramsRead"), int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture)); return; } throw Globals.NotSupported($"Unexpected: {paramsReadSource}"); } private void ILGenParamsReadSource(string paramsReadSource, bool value) { Match match = ParamsReadRegex().Match(paramsReadSource); if (match.Success) { ilg.StoreArrayElement(ilg.GetLocal("paramsRead"), int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture), value); return; } throw Globals.NotSupported($"Unexpected: {paramsReadSource}"); } private void ILGenElementElseString(string elementElseString) { if (elementElseString == "throw CreateUnknownNodeException();") { MethodInfo XmlSerializationReader_CreateUnknownNodeException = typeof(XmlSerializationReader).GetMethod( "CreateUnknownNodeException", CodeGenerator.InstanceBindingFlags, Type.EmptyTypes )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_CreateUnknownNodeException); ilg.Throw(); return; } if (elementElseString.StartsWith("UnknownNode(", StringComparison.Ordinal)) { ILGenElseString(elementElseString); return; } throw Globals.NotSupported($"Unexpected: {elementElseString}"); } [RequiresUnreferencedCode("calls WriteSourceEnd")] private void ILGenSet(string source, object value) { WriteSourceBegin(source); ilg.Load(value); WriteSourceEnd(source, value == null ? typeof(object) : value.GetType()); } } }
1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Globalization; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.Text.RegularExpressions; using System.Diagnostics.CodeAnalysis; namespace System.Xml { // ExceptionType enum is used inside XmlConvert to specify which type of exception should be thrown at some of the verification and exception creating methods internal enum ExceptionType { ArgumentException, XmlException, } // Options for serializing and deserializing DateTime public enum XmlDateTimeSerializationMode { Local, Utc, Unspecified, RoundtripKind, } /// <devdoc> /// Encodes and decodes XML names according to /// the "Encoding of arbitrary Unicode Characters in XML Names" specification. /// </devdoc> public class XmlConvert { internal static char[] crt = new char[] { '\n', '\r', '\t' }; /// <devdoc> /// <para> /// Converts names, such /// as DataTable or /// DataColumn names, that contain characters that are not permitted in /// XML names to valid names.</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? EncodeName(string? name) { return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/); } /// <devdoc> /// <para> Verifies the name is valid /// according to production [7] in the XML spec.</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? EncodeNmToken(string? name) { return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/); } /// <devdoc> /// <para>Converts names, such as DataTable or DataColumn names, that contain /// characters that are not permitted in XML names to valid names.</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? EncodeLocalName(string? name) { return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/); } /// <devdoc> /// <para> /// Transforms an XML name into an object name (such as DataTable or DataColumn).</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? DecodeName(string? name) { if (string.IsNullOrEmpty(name)) return name; StringBuilder? bufBld = null; int length = name.Length; int copyPosition = 0; int underscorePos = name.IndexOf('_'); MatchCollection? mc; IEnumerator? en; if (underscorePos >= 0) { if (s_decodeCharPattern == null) { s_decodeCharPattern = new Regex("_[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } mc = s_decodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } else { return name; } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index; } for (int position = 0; position < length - EncodedCharLength + 1; position++) { if (position == matchPos) { if (en!.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index; } if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append(name, copyPosition, position - copyPosition); if (name[position + 6] != '_') { //_x1234_ int u = FromHex(name[position + 2]) * 0x10000000 + FromHex(name[position + 3]) * 0x1000000 + FromHex(name[position + 4]) * 0x100000 + FromHex(name[position + 5]) * 0x10000 + FromHex(name[position + 6]) * 0x1000 + FromHex(name[position + 7]) * 0x100 + FromHex(name[position + 8]) * 0x10 + FromHex(name[position + 9]); if (u >= 0x00010000) { if (u <= 0x0010ffff) { //convert to two chars copyPosition = position + EncodedCharLength + 4; char lowChar, highChar; XmlCharType.SplitSurrogateChar(u, out lowChar, out highChar); bufBld.Append(highChar); bufBld.Append(lowChar); } //else bad ucs-4 char don't convert } else { //convert to single char copyPosition = position + EncodedCharLength + 4; bufBld.Append((char)u); } position += EncodedCharLength - 1 + 4; //just skip } else { copyPosition = position + EncodedCharLength; bufBld.Append((char)( FromHex(name[position + 2]) * 0x1000 + FromHex(name[position + 3]) * 0x100 + FromHex(name[position + 4]) * 0x10 + FromHex(name[position + 5]))); position += EncodedCharLength - 1; } } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld!.Append(name, copyPosition, length - copyPosition); } return bufBld!.ToString(); } } [return: NotNullIfNotNull("name")] private static string? EncodeName(string? name, /*Name_not_NmToken*/ bool first, bool local) { if (string.IsNullOrEmpty(name)) { return name; } StringBuilder? bufBld = null; int length = name.Length; int copyPosition = 0; int position = 0; int underscorePos = name.IndexOf('_'); MatchCollection? mc; IEnumerator? en = null; if (underscorePos >= 0) { if (s_encodeCharPattern == null) { s_encodeCharPattern = new Regex("(?<=_)[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } mc = s_encodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index - 1; } if (first) { if ((!XmlCharType.IsStartNCNameCharXml4e(name[0]) && (local || (!local && name[0] != ':'))) || matchPos == 0) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append("_x"); if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1])) { int x = name[0]; int y = name[1]; int u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append($"{u:X8}"); position++; copyPosition = 2; } else { bufBld.Append($"{(int)name[0]:X4}"); copyPosition = 1; } bufBld.Append('_'); position++; if (matchPos == 0) if (en!.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index - 1; } } } for (; position < length; position++) { if ((local && !XmlCharType.IsNCNameCharXml4e(name[position])) || (!local && !XmlCharType.IsNameCharXml4e(name[position])) || (matchPos == position)) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } if (matchPos == position) if (en!.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index - 1; } bufBld.Append(name, copyPosition, position - copyPosition); bufBld.Append("_x"); if ((length > position + 1) && XmlCharType.IsHighSurrogate(name[position]) && XmlCharType.IsLowSurrogate(name[position + 1])) { int x = name[position]; int y = name[position + 1]; int u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append($"{u:X8}"); copyPosition = position + 2; position++; } else { bufBld.Append($"{(int)name[position]:X4}"); copyPosition = position + 1; } bufBld.Append('_'); } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld!.Append(name, copyPosition, length - copyPosition); } return bufBld!.ToString(); } } private const int EncodedCharLength = 7; // ("_xFFFF_".Length); private static volatile Regex? s_encodeCharPattern; private static volatile Regex? s_decodeCharPattern; private static int FromHex(char digit) { return HexConverter.FromChar(digit); } internal static byte[] FromBinHexString(string s) { return FromBinHexString(s, true); } internal static byte[] FromBinHexString(string s!!, bool allowOddCount) { return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount); } internal static string ToBinHexString(byte[] inArray!!) { return BinHexEncoder.Encode(inArray, 0, inArray.Length); } // // Verification methods for strings /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyName(string name!!) { if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName); } // parse name int endPos = ValidateNames.ParseNameNoNamespaces(name, 0); if (endPos != name.Length) { // did not parse to the end -> there is invalid character at endPos throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException); } return name; } internal static Exception? TryVerifyName(string name) { if (string.IsNullOrEmpty(name)) { return new XmlException(SR.Xml_EmptyName, string.Empty); } int endPos = ValidateNames.ParseNameNoNamespaces(name, 0); if (endPos != name.Length) { return new XmlException(endPos == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } return null; } internal static string VerifyQName(string name, ExceptionType exceptionType) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } int endPos = ValidateNames.ParseQName(name, 0, out _); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNCName(string name) { return VerifyNCName(name, ExceptionType.XmlException); } internal static string VerifyNCName(string name!!, ExceptionType exceptionType) { if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName); } int end = ValidateNames.ParseNCName(name, 0); if (end != name.Length) { // If the string is not a valid NCName, then throw or return false throw CreateInvalidNameCharException(name, end, exceptionType); } return name; } internal static Exception? TryVerifyNCName(string name) { int len = ValidateNames.ParseNCName(name); if (len == 0 || len != name.Length) { return ValidateNames.GetInvalidNameException(name, 0, len); } return null; } /// <devdoc> /// <para> /// </para> /// </devdoc> [return: NotNullIfNotNull("token")] public static string? VerifyTOKEN(string? token) { if (string.IsNullOrEmpty(token)) { return token; } if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) { throw new XmlException(SR.Sch_NotTokenString, token); } return token; } internal static Exception? TryVerifyTOKEN(string token) { if (token == null || token.Length == 0) { return null; } if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) { return new XmlException(SR.Sch_NotTokenString, token); } return null; } /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNMTOKEN(string name) { return VerifyNMTOKEN(name, ExceptionType.XmlException); } internal static string VerifyNMTOKEN(string name!!, ExceptionType exceptionType) { if (name.Length == 0) { throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType); } int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } internal static Exception? TryVerifyNMTOKEN(string name) { if (name == null || name.Length == 0) { return new XmlException(SR.Xml_EmptyName, string.Empty); } int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0); if (endPos != name.Length) { return new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } return null; } internal static Exception? TryVerifyNormalizedString(string str) { if (str.IndexOfAny(crt) != -1) { return new XmlSchemaException(SR.Sch_NotNormalizedString, str); } return null; } // Verification method for XML characters as defined in XML spec production [2] Char. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyXmlChars(string content!!) { VerifyCharData(content, ExceptionType.XmlException); return content; } // Verification method for XML public ID characters as defined in XML spec production [13] PubidChar. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyPublicId(string publicId!!) { // returns the position of invalid character or -1 int pos = XmlCharType.IsPublicId(publicId); if (pos != -1) { throw CreateInvalidCharException(publicId, pos, ExceptionType.XmlException); } return publicId; } // Verification method for XML whitespace characters as defined in XML spec production [3] S. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyWhitespace(string content!!) { // returns the position of invalid character or -1 int pos = XmlCharType.IsOnlyWhitespaceWithPos(content); if (pos != -1) { throw new XmlException(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1); } return content; } // // Verification methods for single characters and surrogates // // In cases where the direct call into XmlCharType would not get automatically inlined (because of the use of byte* field), // direct access to the XmlCharType.charProperties is used instead (= manual inlining). // // Start name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar // combined with the production [4] NameStartChar of XML 1.0 spec public static bool IsStartNCNameChar(char ch) { return XmlCharType.IsStartNCNameSingleChar(ch); } // Name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar // combined with the production [4] NameChar of XML 1.0 spec public static bool IsNCNameChar(char ch) { return XmlCharType.IsNCNameSingleChar(ch); } // Valid XML character - as defined in XML 1.0 spec (fifth edition) production [2] Char public static bool IsXmlChar(char ch) { return XmlCharType.IsCharData(ch); } public static bool IsXmlSurrogatePair(char lowChar, char highChar) { return XmlCharType.IsHighSurrogate(highChar) && XmlCharType.IsLowSurrogate(lowChar); } // Valid PUBLIC ID character - as defined in XML 1.0 spec (fifth edition) production [13] PublidChar public static bool IsPublicIdChar(char ch) { return XmlCharType.IsPubidChar(ch); } // Valid Xml whitespace - as defined in XML 1.0 spec (fifth edition) production [3] S public static bool IsWhitespaceChar(char ch) { return XmlCharType.IsWhiteSpace(ch); } // Value convertors: // // String representation of Base types in XML (xsd) sometimes differ from // one common language runtime offer and for all types it has to be locale independent. // o -- means that XmlConvert pass through to common language runtime converter with InvariantInfo FormatInfo // x -- means we doing something special to make a conversion. // // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Tim Str uid // ------------------------------------------------------------------------------ // Boolean x // Char o // SByte o // Byte o // Int16 o // UInt16 o // Int32 o // UInt32 o // Int64 o // UInt64 o // Single x // Double x // Decimal o // DateTime x // String x o o o o o o o o o o x x o o x // Guid x // ----------------------------------------------------------------------------- public static string ToString(bool value) { return value ? "true" : "false"; } public static string ToString(char value) { return value.ToString(); } public static string ToString(decimal value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { if (float.IsNegativeInfinity(value)) return "-INF"; if (float.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero((double)value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } public static string ToString(double value) { if (double.IsNegativeInfinity(value)) return "-INF"; if (double.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero(value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } public static string ToString(TimeSpan value) { return new XsdDuration(value).ToString(); } [Obsolete("Use XmlConvert.ToString() that accepts an XmlDateTimeSerializationMode instead.")] public static string ToString(DateTime value) { return ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz"); } public static string ToString(DateTime value, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return value.ToString(format, DateTimeFormatInfo.InvariantInfo); } public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption) { switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: value = SwitchToLocalTime(value); break; case XmlDateTimeSerializationMode.Utc: value = SwitchToUtcTime(value); break; case XmlDateTimeSerializationMode.Unspecified: value = new DateTime(value.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, nameof(dateTimeOption))); } XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value) { XsdDateTime xsdDateTime = new XsdDateTime(value); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return value.ToString(format, DateTimeFormatInfo.InvariantInfo); } public static string ToString(Guid value) { return value.ToString(); } public static bool ToBoolean(string s) { s = TrimString(s); if (s == "1" || s == "true") return true; if (s == "0" || s == "false") return false; throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } internal static Exception? TryToBoolean(string s, out bool result) { s = TrimString(s); if (s == "0" || s == "false") { result = false; return null; } else if (s == "1" || s == "true") { result = true; return null; } result = false; return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } public static char ToChar(string s!!) { if (s.Length != 1) { throw new FormatException(SR.XmlConvert_NotOneCharString); } return s[0]; } internal static Exception? TryToChar(string s, out char result) { if (!char.TryParse(s, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Char")); } return null; } public static decimal ToDecimal(string s) { return decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToDecimal(string s, out decimal result) { if (!decimal.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Decimal")); } return null; } internal static decimal ToInteger(string s) { return decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInteger(string s, out decimal result) { if (!decimal.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Integer")); } return null; } [CLSCompliant(false)] public static sbyte ToSByte(string s) { return sbyte.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToSByte(string s, out sbyte result) { if (!sbyte.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "SByte")); } return null; } public static short ToInt16(string s) { return short.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInt16(string s, out short result) { if (!short.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int16")); } return null; } public static int ToInt32(string s) { return int.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInt32(string s, out int result) { if (!int.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int32")); } return null; } public static long ToInt64(string s) { return long.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInt64(string s, out long result) { if (!long.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int64")); } return null; } public static byte ToByte(string s) { return byte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToByte(string s, out byte result) { if (!byte.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Byte")); } return null; } [CLSCompliant(false)] public static ushort ToUInt16(string s) { return ushort.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToUInt16(string s, out ushort result) { if (!ushort.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt16")); } return null; } [CLSCompliant(false)] public static uint ToUInt32(string s) { return uint.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToUInt32(string s, out uint result) { if (!uint.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt32")); } return null; } [CLSCompliant(false)] public static ulong ToUInt64(string s) { return ulong.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToUInt64(string s, out ulong result) { if (!ulong.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt64")); } return null; } public static float ToSingle(string s) { s = TrimString(s); if (s == "-INF") return float.NegativeInfinity; if (s == "INF") return float.PositiveInfinity; float f = float.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo); if (f == 0 && s[0] == '-') { return -0f; } return f; } internal static Exception? TryToSingle(string s, out float result) { s = TrimString(s); if (s == "-INF") { result = float.NegativeInfinity; return null; } else if (s == "INF") { result = float.PositiveInfinity; return null; } else if (!float.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Single")); } if (result == 0 && s[0] == '-') { result = -0f; } return null; } public static double ToDouble(string s) { s = TrimString(s); if (s == "-INF") return double.NegativeInfinity; if (s == "INF") return double.PositiveInfinity; double dVal = double.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); if (dVal == 0 && s[0] == '-') { return -0d; } return dVal; } internal static Exception? TryToDouble(string s, out double result) { s = TrimString(s); if (s == "-INF") { result = double.NegativeInfinity; return null; } else if (s == "INF") { result = double.PositiveInfinity; return null; } else if (!double.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Double")); } if (result == 0 && s[0] == '-') { result = -0d; } return null; } internal static double ToXPathDouble(object? o) { if (o is string str) { str = TrimString(str); if (str.Length != 0 && str[0] != '+') { double d; if (double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out d)) { return d; } } return double.NaN; } if (o is double oDouble) { return oDouble; } if (o is bool oBool) { return oBool ? 1.0 : 0.0; } try { return Convert.ToDouble(o, NumberFormatInfo.InvariantInfo); } catch (FormatException) { } catch (OverflowException) { } catch (ArgumentNullException) { } return double.NaN; } internal static string? ToXPathString(object? value) { if (value is string s) { return s; } else if (value is double) { return ((double)value).ToString("R", NumberFormatInfo.InvariantInfo); } else if (value is bool) { return (bool)value ? "true" : "false"; } else { return Convert.ToString(value, NumberFormatInfo.InvariantInfo); } } internal static double XPathRound(double value) { double temp = Math.Round(value); return (value - temp == 0.5) ? temp + 1 : temp; } public static TimeSpan ToTimeSpan(string s) { XsdDuration duration; TimeSpan timeSpan; try { duration = new XsdDuration(s); } catch (Exception) { // Remap exception for v1 compatibility throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "TimeSpan")); } timeSpan = duration.ToTimeSpan(); return timeSpan; } internal static Exception? TryToTimeSpan(string s, out TimeSpan result) { XsdDuration duration; Exception? exception; exception = XsdDuration.TryParse(s, out duration); if (exception != null) { result = TimeSpan.MinValue; return exception; } else { return duration.TryToTimeSpan(out result); } } // use AllDateTimeFormats property to access the formats private static volatile string[]? s_allDateTimeFormats; // NOTE: Do not use this property for reference comparison. It may not be unique. private static string[] AllDateTimeFormats { get { if (s_allDateTimeFormats == null) { CreateAllDateTimeFormats(); } return s_allDateTimeFormats!; } } private static void CreateAllDateTimeFormats() { if (s_allDateTimeFormats == null) { // no locking; the array is immutable so it's not a problem that it may get initialized more than once s_allDateTimeFormats = new string[] { "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzzzzz", //dateTime "yyyy-MM-ddTHH:mm:ss.FFFFFFF", "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ", "HH:mm:ss.FFFFFFF", //time "HH:mm:ss.FFFFFFFZ", "HH:mm:ss.FFFFFFFzzzzzz", "yyyy-MM-dd", // date "yyyy-MM-ddZ", "yyyy-MM-ddzzzzzz", "yyyy-MM", // yearMonth "yyyy-MMZ", "yyyy-MMzzzzzz", "yyyy", // year "yyyyZ", "yyyyzzzzzz", "--MM-dd", // monthDay "--MM-ddZ", "--MM-ddzzzzzz", "---dd", // day "---ddZ", "---ddzzzzzz", "--MM--", // month "--MM--Z", "--MM--zzzzzz", }; } } [Obsolete("Use XmlConvert.ToDateTime() that accepts an XmlDateTimeSerializationMode instead.")] public static DateTime ToDateTime(string s) { return ToDateTime(s, AllDateTimeFormats); } public static DateTime ToDateTime(string s, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTime ToDateTime(string s, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string[] formats) { return DateTime.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption) { XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTime dt = (DateTime)xsdDateTime; switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: dt = SwitchToLocalTime(dt); break; case XmlDateTimeSerializationMode.Utc: dt = SwitchToUtcTime(dt); break; case XmlDateTimeSerializationMode.Unspecified: dt = new DateTime(dt.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, nameof(dateTimeOption))); } return dt; } public static DateTimeOffset ToDateTimeOffset(string s!!) { XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime; return dateTimeOffset; } public static DateTimeOffset ToDateTimeOffset(string s!!, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return DateTimeOffset.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTimeOffset ToDateTimeOffset(string s!!, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string[] formats) { return DateTimeOffset.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static Guid ToGuid(string s) { return new Guid(s); } internal static Exception? TryToGuid(string s, out Guid result) { Exception? exception = null; result = Guid.Empty; try { result = new Guid(s); } catch (ArgumentException) { exception = new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Guid")); } catch (FormatException) { exception = new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Guid")); } return exception; } private static DateTime SwitchToLocalTime(DateTime value) => value.Kind switch { DateTimeKind.Local => value, DateTimeKind.Unspecified => new DateTime(value.Ticks, DateTimeKind.Local), DateTimeKind.Utc => value.ToLocalTime(), _ => value, }; private static DateTime SwitchToUtcTime(DateTime value) => value.Kind switch { DateTimeKind.Utc => value, DateTimeKind.Unspecified => new DateTime(value.Ticks, DateTimeKind.Utc), DateTimeKind.Local => value.ToUniversalTime(), _ => value, }; internal static Uri ToUri(string? s) { if (!string.IsNullOrEmpty(s)) { // string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } Uri? uri; if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } return uri; } internal static Exception? TryToUri(string s, out Uri? result) { result = null; if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } return null; } // Compares the given character interval and string and returns true if the characters are identical internal static bool StrEqual(char[]? chars, int strPos1, int strLen1, string str2) { if (strLen1 != str2.Length) { return false; } Debug.Assert(chars != null); int i = 0; while (i < strLen1 && chars[strPos1 + i] == str2[i]) { i++; } return i == strLen1; } // XML whitespace characters, <spec>http://www.w3.org/TR/REC-xml#NT-S</spec> internal static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; // Trim a string using XML whitespace characters internal static string TrimString(string value) { return value.Trim(WhitespaceChars); } // Trim beginning of a string using XML whitespace characters internal static string TrimStringStart(string value) { return value.TrimStart(WhitespaceChars); } // Trim end of a string using XML whitespace characters internal static string TrimStringEnd(string value) { return value.TrimEnd(WhitespaceChars); } // Split a string into a whitespace-separated list of tokens internal static string[] SplitString(string value) { return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries); } internal static string[] SplitString(string value, StringSplitOptions splitStringOptions) { return value.Split(WhitespaceChars, splitStringOptions); } internal static bool IsNegativeZero(double value) { // Simple equals function will report that -0 is equal to +0, so compare bits instead if (value == 0 && BitConverter.DoubleToInt64Bits(value) == BitConverter.DoubleToInt64Bits(-0e0)) { return true; } return false; } internal static void VerifyCharData(string? data, ExceptionType exceptionType) { VerifyCharData(data, exceptionType, exceptionType); } internal static void VerifyCharData(string? data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) { if (data == null || data.Length == 0) { return; } int i = 0; int len = data.Length; while (true) { while (i < len && XmlCharType.IsCharData(data[i])) { i++; } if (i == len) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == len) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1); } } throw CreateInvalidCharException(data, i, invCharExceptionType); } } internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType) { if (data == null || len == 0) { return; } int i = offset; int endPos = offset + len; while (true) { while (i < endPos && XmlCharType.IsCharData(data[i])) { i++; } if (i == endPos) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == endPos) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1); } } throw CreateInvalidCharException(data, len, i, exceptionType); } } internal static string EscapeValueForDebuggerDisplay(string value) { StringBuilder? sb = null; int i = 0; int start = 0; while (i < value.Length) { char ch = value[i]; if ((int)ch < 0x20 || ch == '"') { if (sb == null) { sb = new StringBuilder(value.Length + 4); } if (i - start > 0) { sb.Append(value, start, i - start); } start = i + 1; switch (ch) { case '"': sb.Append("\\\""); break; case '\r': sb.Append("\\r"); break; case '\n': sb.Append("\\n"); break; case '\t': sb.Append("\\t"); break; default: sb.Append(ch); break; } } i++; } if (sb == null) { return value; } if (i - start > 0) { sb.Append(value, start, i - start); } return sb.ToString(); } internal static Exception CreateException(string res, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(res); case ExceptionType.XmlException: default: return new XmlException(res, string.Empty, lineNo, linePos); } } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType) { return CreateException(res, arg, exceptionType, 0, 0); } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(string.Format(res, arg)); case ExceptionType.XmlException: default: return new XmlException(res, arg, lineNo, linePos); } } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType) { return CreateException(res, args, exceptionType, 0, 0); } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(string.Format(res, args)); case ExceptionType.XmlException: default: return new XmlException(res, args, lineNo, linePos); } } internal static Exception CreateInvalidSurrogatePairException(char low, char hi) { return CreateInvalidSurrogatePairException(low, hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType) { return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType, int lineNo, int linePos) { string[] args = new string[] { ((uint)hi).ToString("X", CultureInfo.InvariantCulture), ((uint)low).ToString("X", CultureInfo.InvariantCulture) }; return CreateException(SR.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos); } internal static Exception CreateInvalidHighSurrogateCharException(char hi) { return CreateInvalidHighSurrogateCharException(hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType) { return CreateInvalidHighSurrogateCharException(hi, exceptionType, 0, 0); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos) { return CreateException(SR.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString("X", CultureInfo.InvariantCulture), exceptionType, lineNo, linePos); } internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(string data, int invCharPos) { return CreateInvalidCharException(data, invCharPos, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(string data, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(char invChar, char nextChar) { return CreateInvalidCharException(invChar, nextChar, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(char invChar, char nextChar, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(invChar, nextChar), exceptionType); } internal static Exception CreateInvalidNameCharException(string name, int index, ExceptionType exceptionType) { return CreateException(index == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Globalization; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.Text.RegularExpressions; using System.Diagnostics.CodeAnalysis; namespace System.Xml { // ExceptionType enum is used inside XmlConvert to specify which type of exception should be thrown at some of the verification and exception creating methods internal enum ExceptionType { ArgumentException, XmlException, } // Options for serializing and deserializing DateTime public enum XmlDateTimeSerializationMode { Local, Utc, Unspecified, RoundtripKind, } /// <devdoc> /// Encodes and decodes XML names according to /// the "Encoding of arbitrary Unicode Characters in XML Names" specification. /// </devdoc> public partial class XmlConvert { internal static char[] crt = new char[] { '\n', '\r', '\t' }; /// <devdoc> /// <para> /// Converts names, such /// as DataTable or /// DataColumn names, that contain characters that are not permitted in /// XML names to valid names.</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? EncodeName(string? name) { return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/); } /// <devdoc> /// <para> Verifies the name is valid /// according to production [7] in the XML spec.</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? EncodeNmToken(string? name) { return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/); } /// <devdoc> /// <para>Converts names, such as DataTable or DataColumn names, that contain /// characters that are not permitted in XML names to valid names.</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? EncodeLocalName(string? name) { return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/); } /// <devdoc> /// <para> /// Transforms an XML name into an object name (such as DataTable or DataColumn).</para> /// </devdoc> [return: NotNullIfNotNull("name")] public static string? DecodeName(string? name) { if (string.IsNullOrEmpty(name)) return name; StringBuilder? bufBld = null; int length = name.Length; int copyPosition = 0; int underscorePos = name.IndexOf('_'); MatchCollection? mc; IEnumerator? en; if (underscorePos >= 0) { mc = DecodeCharRegex().Matches(name, underscorePos); en = mc.GetEnumerator(); } else { return name; } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index; } for (int position = 0; position < length - EncodedCharLength + 1; position++) { if (position == matchPos) { if (en!.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index; } if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append(name, copyPosition, position - copyPosition); if (name[position + 6] != '_') { //_x1234_ int u = FromHex(name[position + 2]) * 0x10000000 + FromHex(name[position + 3]) * 0x1000000 + FromHex(name[position + 4]) * 0x100000 + FromHex(name[position + 5]) * 0x10000 + FromHex(name[position + 6]) * 0x1000 + FromHex(name[position + 7]) * 0x100 + FromHex(name[position + 8]) * 0x10 + FromHex(name[position + 9]); if (u >= 0x00010000) { if (u <= 0x0010ffff) { //convert to two chars copyPosition = position + EncodedCharLength + 4; char lowChar, highChar; XmlCharType.SplitSurrogateChar(u, out lowChar, out highChar); bufBld.Append(highChar); bufBld.Append(lowChar); } //else bad ucs-4 char don't convert } else { //convert to single char copyPosition = position + EncodedCharLength + 4; bufBld.Append((char)u); } position += EncodedCharLength - 1 + 4; //just skip } else { copyPosition = position + EncodedCharLength; bufBld.Append((char)( FromHex(name[position + 2]) * 0x1000 + FromHex(name[position + 3]) * 0x100 + FromHex(name[position + 4]) * 0x10 + FromHex(name[position + 5]))); position += EncodedCharLength - 1; } } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld!.Append(name, copyPosition, length - copyPosition); } return bufBld!.ToString(); } } [return: NotNullIfNotNull("name")] private static string? EncodeName(string? name, /*Name_not_NmToken*/ bool first, bool local) { if (string.IsNullOrEmpty(name)) { return name; } StringBuilder? bufBld = null; int length = name.Length; int copyPosition = 0; int position = 0; int underscorePos = name.IndexOf('_'); MatchCollection? mc; IEnumerator? en = null; if (underscorePos >= 0) { mc = EncodeCharRegex().Matches(name, underscorePos); en = mc.GetEnumerator(); } int matchPos = -1; if (en != null && en.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index - 1; } if (first) { if ((!XmlCharType.IsStartNCNameCharXml4e(name[0]) && (local || (!local && name[0] != ':'))) || matchPos == 0) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } bufBld.Append("_x"); if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1])) { int x = name[0]; int y = name[1]; int u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append($"{u:X8}"); position++; copyPosition = 2; } else { bufBld.Append($"{(int)name[0]:X4}"); copyPosition = 1; } bufBld.Append('_'); position++; if (matchPos == 0) if (en!.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index - 1; } } } for (; position < length; position++) { if ((local && !XmlCharType.IsNCNameCharXml4e(name[position])) || (!local && !XmlCharType.IsNameCharXml4e(name[position])) || (matchPos == position)) { if (bufBld == null) { bufBld = new StringBuilder(length + 20); } if (matchPos == position) if (en!.MoveNext()) { Match m = (Match)en.Current!; matchPos = m.Index - 1; } bufBld.Append(name, copyPosition, position - copyPosition); bufBld.Append("_x"); if ((length > position + 1) && XmlCharType.IsHighSurrogate(name[position]) && XmlCharType.IsLowSurrogate(name[position + 1])) { int x = name[position]; int y = name[position + 1]; int u = XmlCharType.CombineSurrogateChar(y, x); bufBld.Append($"{u:X8}"); copyPosition = position + 2; position++; } else { bufBld.Append($"{(int)name[position]:X4}"); copyPosition = position + 1; } bufBld.Append('_'); } } if (copyPosition == 0) { return name; } else { if (copyPosition < length) { bufBld!.Append(name, copyPosition, length - copyPosition); } return bufBld!.ToString(); } } private const int EncodedCharLength = 7; // ("_xFFFF_".Length); [RegexGenerator("_[Xx][0-9a-fA-F]{4}(?:_|[0-9a-fA-F]{4}_)")] private static partial Regex DecodeCharRegex(); [RegexGenerator("(?<=_)[Xx][0-9a-fA-F]{4}(?:_|[0-9a-fA-F]{4}_)")] private static partial Regex EncodeCharRegex(); private static int FromHex(char digit) { return HexConverter.FromChar(digit); } internal static byte[] FromBinHexString(string s) { return FromBinHexString(s, true); } internal static byte[] FromBinHexString(string s!!, bool allowOddCount) { return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount); } internal static string ToBinHexString(byte[] inArray!!) { return BinHexEncoder.Encode(inArray, 0, inArray.Length); } // // Verification methods for strings /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyName(string name!!) { if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName); } // parse name int endPos = ValidateNames.ParseNameNoNamespaces(name, 0); if (endPos != name.Length) { // did not parse to the end -> there is invalid character at endPos throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException); } return name; } internal static Exception? TryVerifyName(string name) { if (string.IsNullOrEmpty(name)) { return new XmlException(SR.Xml_EmptyName, string.Empty); } int endPos = ValidateNames.ParseNameNoNamespaces(name, 0); if (endPos != name.Length) { return new XmlException(endPos == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } return null; } internal static string VerifyQName(string name, ExceptionType exceptionType) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } int endPos = ValidateNames.ParseQName(name, 0, out _); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNCName(string name) { return VerifyNCName(name, ExceptionType.XmlException); } internal static string VerifyNCName(string name!!, ExceptionType exceptionType) { if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName); } int end = ValidateNames.ParseNCName(name, 0); if (end != name.Length) { // If the string is not a valid NCName, then throw or return false throw CreateInvalidNameCharException(name, end, exceptionType); } return name; } internal static Exception? TryVerifyNCName(string name) { int len = ValidateNames.ParseNCName(name); if (len == 0 || len != name.Length) { return ValidateNames.GetInvalidNameException(name, 0, len); } return null; } /// <devdoc> /// <para> /// </para> /// </devdoc> [return: NotNullIfNotNull("token")] public static string? VerifyTOKEN(string? token) { if (string.IsNullOrEmpty(token)) { return token; } if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) { throw new XmlException(SR.Sch_NotTokenString, token); } return token; } internal static Exception? TryVerifyTOKEN(string token) { if (token == null || token.Length == 0) { return null; } if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) { return new XmlException(SR.Sch_NotTokenString, token); } return null; } /// <devdoc> /// <para> /// </para> /// </devdoc> public static string VerifyNMTOKEN(string name) { return VerifyNMTOKEN(name, ExceptionType.XmlException); } internal static string VerifyNMTOKEN(string name!!, ExceptionType exceptionType) { if (name.Length == 0) { throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType); } int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } return name; } internal static Exception? TryVerifyNMTOKEN(string name) { if (name == null || name.Length == 0) { return new XmlException(SR.Xml_EmptyName, string.Empty); } int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0); if (endPos != name.Length) { return new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } return null; } internal static Exception? TryVerifyNormalizedString(string str) { if (str.IndexOfAny(crt) != -1) { return new XmlSchemaException(SR.Sch_NotNormalizedString, str); } return null; } // Verification method for XML characters as defined in XML spec production [2] Char. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyXmlChars(string content!!) { VerifyCharData(content, ExceptionType.XmlException); return content; } // Verification method for XML public ID characters as defined in XML spec production [13] PubidChar. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyPublicId(string publicId!!) { // returns the position of invalid character or -1 int pos = XmlCharType.IsPublicId(publicId); if (pos != -1) { throw CreateInvalidCharException(publicId, pos, ExceptionType.XmlException); } return publicId; } // Verification method for XML whitespace characters as defined in XML spec production [3] S. // Throws XmlException if invalid character is found, otherwise returns the input string. public static string VerifyWhitespace(string content!!) { // returns the position of invalid character or -1 int pos = XmlCharType.IsOnlyWhitespaceWithPos(content); if (pos != -1) { throw new XmlException(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1); } return content; } // // Verification methods for single characters and surrogates // // In cases where the direct call into XmlCharType would not get automatically inlined (because of the use of byte* field), // direct access to the XmlCharType.charProperties is used instead (= manual inlining). // // Start name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar // combined with the production [4] NameStartChar of XML 1.0 spec public static bool IsStartNCNameChar(char ch) { return XmlCharType.IsStartNCNameSingleChar(ch); } // Name character types - as defined in Namespaces XML 1.0 spec (second edition) production [6] NCNameStartChar // combined with the production [4] NameChar of XML 1.0 spec public static bool IsNCNameChar(char ch) { return XmlCharType.IsNCNameSingleChar(ch); } // Valid XML character - as defined in XML 1.0 spec (fifth edition) production [2] Char public static bool IsXmlChar(char ch) { return XmlCharType.IsCharData(ch); } public static bool IsXmlSurrogatePair(char lowChar, char highChar) { return XmlCharType.IsHighSurrogate(highChar) && XmlCharType.IsLowSurrogate(lowChar); } // Valid PUBLIC ID character - as defined in XML 1.0 spec (fifth edition) production [13] PublidChar public static bool IsPublicIdChar(char ch) { return XmlCharType.IsPubidChar(ch); } // Valid Xml whitespace - as defined in XML 1.0 spec (fifth edition) production [3] S public static bool IsWhitespaceChar(char ch) { return XmlCharType.IsWhiteSpace(ch); } // Value convertors: // // String representation of Base types in XML (xsd) sometimes differ from // one common language runtime offer and for all types it has to be locale independent. // o -- means that XmlConvert pass through to common language runtime converter with InvariantInfo FormatInfo // x -- means we doing something special to make a conversion. // // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Tim Str uid // ------------------------------------------------------------------------------ // Boolean x // Char o // SByte o // Byte o // Int16 o // UInt16 o // Int32 o // UInt32 o // Int64 o // UInt64 o // Single x // Double x // Decimal o // DateTime x // String x o o o o o o o o o o x x o o x // Guid x // ----------------------------------------------------------------------------- public static string ToString(bool value) { return value ? "true" : "false"; } public static string ToString(char value) { return value.ToString(); } public static string ToString(decimal value) { return value.ToString(null, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { if (float.IsNegativeInfinity(value)) return "-INF"; if (float.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero((double)value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } public static string ToString(double value) { if (double.IsNegativeInfinity(value)) return "-INF"; if (double.IsPositiveInfinity(value)) return "INF"; if (IsNegativeZero(value)) { return ("-0"); } return value.ToString("R", NumberFormatInfo.InvariantInfo); } public static string ToString(TimeSpan value) { return new XsdDuration(value).ToString(); } [Obsolete("Use XmlConvert.ToString() that accepts an XmlDateTimeSerializationMode instead.")] public static string ToString(DateTime value) { return ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz"); } public static string ToString(DateTime value, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return value.ToString(format, DateTimeFormatInfo.InvariantInfo); } public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption) { switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: value = SwitchToLocalTime(value); break; case XmlDateTimeSerializationMode.Utc: value = SwitchToUtcTime(value); break; case XmlDateTimeSerializationMode.Unspecified: value = new DateTime(value.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, nameof(dateTimeOption))); } XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value) { XsdDateTime xsdDateTime = new XsdDateTime(value); return xsdDateTime.ToString(); } public static string ToString(DateTimeOffset value, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return value.ToString(format, DateTimeFormatInfo.InvariantInfo); } public static string ToString(Guid value) { return value.ToString(); } public static bool ToBoolean(string s) { s = TrimString(s); if (s == "1" || s == "true") return true; if (s == "0" || s == "false") return false; throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } internal static Exception? TryToBoolean(string s, out bool result) { s = TrimString(s); if (s == "0" || s == "false") { result = false; return null; } else if (s == "1" || s == "true") { result = true; return null; } result = false; return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } public static char ToChar(string s!!) { if (s.Length != 1) { throw new FormatException(SR.XmlConvert_NotOneCharString); } return s[0]; } internal static Exception? TryToChar(string s, out char result) { if (!char.TryParse(s, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Char")); } return null; } public static decimal ToDecimal(string s) { return decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToDecimal(string s, out decimal result) { if (!decimal.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Decimal")); } return null; } internal static decimal ToInteger(string s) { return decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInteger(string s, out decimal result) { if (!decimal.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Integer")); } return null; } [CLSCompliant(false)] public static sbyte ToSByte(string s) { return sbyte.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToSByte(string s, out sbyte result) { if (!sbyte.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "SByte")); } return null; } public static short ToInt16(string s) { return short.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInt16(string s, out short result) { if (!short.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int16")); } return null; } public static int ToInt32(string s) { return int.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInt32(string s, out int result) { if (!int.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int32")); } return null; } public static long ToInt64(string s) { return long.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToInt64(string s, out long result) { if (!long.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int64")); } return null; } public static byte ToByte(string s) { return byte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToByte(string s, out byte result) { if (!byte.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Byte")); } return null; } [CLSCompliant(false)] public static ushort ToUInt16(string s) { return ushort.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToUInt16(string s, out ushort result) { if (!ushort.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt16")); } return null; } [CLSCompliant(false)] public static uint ToUInt32(string s) { return uint.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToUInt32(string s, out uint result) { if (!uint.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt32")); } return null; } [CLSCompliant(false)] public static ulong ToUInt64(string s) { return ulong.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } internal static Exception? TryToUInt64(string s, out ulong result) { if (!ulong.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt64")); } return null; } public static float ToSingle(string s) { s = TrimString(s); if (s == "-INF") return float.NegativeInfinity; if (s == "INF") return float.PositiveInfinity; float f = float.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo); if (f == 0 && s[0] == '-') { return -0f; } return f; } internal static Exception? TryToSingle(string s, out float result) { s = TrimString(s); if (s == "-INF") { result = float.NegativeInfinity; return null; } else if (s == "INF") { result = float.PositiveInfinity; return null; } else if (!float.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Single")); } if (result == 0 && s[0] == '-') { result = -0f; } return null; } public static double ToDouble(string s) { s = TrimString(s); if (s == "-INF") return double.NegativeInfinity; if (s == "INF") return double.PositiveInfinity; double dVal = double.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); if (dVal == 0 && s[0] == '-') { return -0d; } return dVal; } internal static Exception? TryToDouble(string s, out double result) { s = TrimString(s); if (s == "-INF") { result = double.NegativeInfinity; return null; } else if (s == "INF") { result = double.PositiveInfinity; return null; } else if (!double.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Double")); } if (result == 0 && s[0] == '-') { result = -0d; } return null; } internal static double ToXPathDouble(object? o) { if (o is string str) { str = TrimString(str); if (str.Length != 0 && str[0] != '+') { double d; if (double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out d)) { return d; } } return double.NaN; } if (o is double oDouble) { return oDouble; } if (o is bool oBool) { return oBool ? 1.0 : 0.0; } try { return Convert.ToDouble(o, NumberFormatInfo.InvariantInfo); } catch (FormatException) { } catch (OverflowException) { } catch (ArgumentNullException) { } return double.NaN; } internal static string? ToXPathString(object? value) { if (value is string s) { return s; } else if (value is double) { return ((double)value).ToString("R", NumberFormatInfo.InvariantInfo); } else if (value is bool) { return (bool)value ? "true" : "false"; } else { return Convert.ToString(value, NumberFormatInfo.InvariantInfo); } } internal static double XPathRound(double value) { double temp = Math.Round(value); return (value - temp == 0.5) ? temp + 1 : temp; } public static TimeSpan ToTimeSpan(string s) { XsdDuration duration; TimeSpan timeSpan; try { duration = new XsdDuration(s); } catch (Exception) { // Remap exception for v1 compatibility throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "TimeSpan")); } timeSpan = duration.ToTimeSpan(); return timeSpan; } internal static Exception? TryToTimeSpan(string s, out TimeSpan result) { XsdDuration duration; Exception? exception; exception = XsdDuration.TryParse(s, out duration); if (exception != null) { result = TimeSpan.MinValue; return exception; } else { return duration.TryToTimeSpan(out result); } } // use AllDateTimeFormats property to access the formats private static volatile string[]? s_allDateTimeFormats; // NOTE: Do not use this property for reference comparison. It may not be unique. private static string[] AllDateTimeFormats { get { if (s_allDateTimeFormats == null) { CreateAllDateTimeFormats(); } return s_allDateTimeFormats!; } } private static void CreateAllDateTimeFormats() { if (s_allDateTimeFormats == null) { // no locking; the array is immutable so it's not a problem that it may get initialized more than once s_allDateTimeFormats = new string[] { "yyyy-MM-ddTHH:mm:ss.FFFFFFFzzzzzz", //dateTime "yyyy-MM-ddTHH:mm:ss.FFFFFFF", "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ", "HH:mm:ss.FFFFFFF", //time "HH:mm:ss.FFFFFFFZ", "HH:mm:ss.FFFFFFFzzzzzz", "yyyy-MM-dd", // date "yyyy-MM-ddZ", "yyyy-MM-ddzzzzzz", "yyyy-MM", // yearMonth "yyyy-MMZ", "yyyy-MMzzzzzz", "yyyy", // year "yyyyZ", "yyyyzzzzzz", "--MM-dd", // monthDay "--MM-ddZ", "--MM-ddzzzzzz", "---dd", // day "---ddZ", "---ddzzzzzz", "--MM--", // month "--MM--Z", "--MM--zzzzzz", }; } } [Obsolete("Use XmlConvert.ToDateTime() that accepts an XmlDateTimeSerializationMode instead.")] public static DateTime ToDateTime(string s) { return ToDateTime(s, AllDateTimeFormats); } public static DateTime ToDateTime(string s, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTime ToDateTime(string s, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string[] formats) { return DateTime.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption) { XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTime dt = (DateTime)xsdDateTime; switch (dateTimeOption) { case XmlDateTimeSerializationMode.Local: dt = SwitchToLocalTime(dt); break; case XmlDateTimeSerializationMode.Utc: dt = SwitchToUtcTime(dt); break; case XmlDateTimeSerializationMode.Unspecified: dt = new DateTime(dt.Ticks, DateTimeKind.Unspecified); break; case XmlDateTimeSerializationMode.RoundtripKind: break; default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, nameof(dateTimeOption))); } return dt; } public static DateTimeOffset ToDateTimeOffset(string s!!) { XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime; return dateTimeOffset; } public static DateTimeOffset ToDateTimeOffset(string s!!, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { return DateTimeOffset.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static DateTimeOffset ToDateTimeOffset(string s!!, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string[] formats) { return DateTimeOffset.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } public static Guid ToGuid(string s) { return new Guid(s); } internal static Exception? TryToGuid(string s, out Guid result) { Exception? exception = null; result = Guid.Empty; try { result = new Guid(s); } catch (ArgumentException) { exception = new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Guid")); } catch (FormatException) { exception = new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Guid")); } return exception; } private static DateTime SwitchToLocalTime(DateTime value) => value.Kind switch { DateTimeKind.Local => value, DateTimeKind.Unspecified => new DateTime(value.Ticks, DateTimeKind.Local), DateTimeKind.Utc => value.ToLocalTime(), _ => value, }; private static DateTime SwitchToUtcTime(DateTime value) => value.Kind switch { DateTimeKind.Utc => value, DateTimeKind.Unspecified => new DateTime(value.Ticks, DateTimeKind.Utc), DateTimeKind.Local => value.ToUniversalTime(), _ => value, }; internal static Uri ToUri(string? s) { if (!string.IsNullOrEmpty(s)) { // string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } Uri? uri; if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } return uri; } internal static Exception? TryToUri(string s, out Uri? result) { result = null; if (s != null && s.Length > 0) { //string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } return null; } // Compares the given character interval and string and returns true if the characters are identical internal static bool StrEqual(char[]? chars, int strPos1, int strLen1, string str2) { if (strLen1 != str2.Length) { return false; } Debug.Assert(chars != null); int i = 0; while (i < strLen1 && chars[strPos1 + i] == str2[i]) { i++; } return i == strLen1; } // XML whitespace characters, <spec>http://www.w3.org/TR/REC-xml#NT-S</spec> internal static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; // Trim a string using XML whitespace characters internal static string TrimString(string value) { return value.Trim(WhitespaceChars); } // Trim beginning of a string using XML whitespace characters internal static string TrimStringStart(string value) { return value.TrimStart(WhitespaceChars); } // Trim end of a string using XML whitespace characters internal static string TrimStringEnd(string value) { return value.TrimEnd(WhitespaceChars); } // Split a string into a whitespace-separated list of tokens internal static string[] SplitString(string value) { return value.Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries); } internal static string[] SplitString(string value, StringSplitOptions splitStringOptions) { return value.Split(WhitespaceChars, splitStringOptions); } internal static bool IsNegativeZero(double value) { // Simple equals function will report that -0 is equal to +0, so compare bits instead if (value == 0 && BitConverter.DoubleToInt64Bits(value) == BitConverter.DoubleToInt64Bits(-0e0)) { return true; } return false; } internal static void VerifyCharData(string? data, ExceptionType exceptionType) { VerifyCharData(data, exceptionType, exceptionType); } internal static void VerifyCharData(string? data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) { if (data == null || data.Length == 0) { return; } int i = 0; int len = data.Length; while (true) { while (i < len && XmlCharType.IsCharData(data[i])) { i++; } if (i == len) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == len) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1); } } throw CreateInvalidCharException(data, i, invCharExceptionType); } } internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType) { if (data == null || len == 0) { return; } int i = offset; int endPos = offset + len; while (true) { while (i < endPos && XmlCharType.IsCharData(data[i])) { i++; } if (i == endPos) { return; } char ch = data[i]; if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 == endPos) { throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1); } ch = data[i + 1]; if (XmlCharType.IsLowSurrogate(ch)) { i += 2; continue; } else { throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1); } } throw CreateInvalidCharException(data, len, i, exceptionType); } } internal static string EscapeValueForDebuggerDisplay(string value) { StringBuilder? sb = null; int i = 0; int start = 0; while (i < value.Length) { char ch = value[i]; if ((int)ch < 0x20 || ch == '"') { if (sb == null) { sb = new StringBuilder(value.Length + 4); } if (i - start > 0) { sb.Append(value, start, i - start); } start = i + 1; switch (ch) { case '"': sb.Append("\\\""); break; case '\r': sb.Append("\\r"); break; case '\n': sb.Append("\\n"); break; case '\t': sb.Append("\\t"); break; default: sb.Append(ch); break; } } i++; } if (sb == null) { return value; } if (i - start > 0) { sb.Append(value, start, i - start); } return sb.ToString(); } internal static Exception CreateException(string res, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(res); case ExceptionType.XmlException: default: return new XmlException(res, string.Empty, lineNo, linePos); } } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType) { return CreateException(res, arg, exceptionType, 0, 0); } internal static Exception CreateException(string res, string arg, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(string.Format(res, arg)); case ExceptionType.XmlException: default: return new XmlException(res, arg, lineNo, linePos); } } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType) { return CreateException(res, args, exceptionType, 0, 0); } internal static Exception CreateException(string res, string[] args, ExceptionType exceptionType, int lineNo, int linePos) { switch (exceptionType) { case ExceptionType.ArgumentException: return new ArgumentException(string.Format(res, args)); case ExceptionType.XmlException: default: return new XmlException(res, args, lineNo, linePos); } } internal static Exception CreateInvalidSurrogatePairException(char low, char hi) { return CreateInvalidSurrogatePairException(low, hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType) { return CreateInvalidSurrogatePairException(low, hi, exceptionType, 0, 0); } internal static Exception CreateInvalidSurrogatePairException(char low, char hi, ExceptionType exceptionType, int lineNo, int linePos) { string[] args = new string[] { ((uint)hi).ToString("X", CultureInfo.InvariantCulture), ((uint)low).ToString("X", CultureInfo.InvariantCulture) }; return CreateException(SR.Xml_InvalidSurrogatePairWithArgs, args, exceptionType, lineNo, linePos); } internal static Exception CreateInvalidHighSurrogateCharException(char hi) { return CreateInvalidHighSurrogateCharException(hi, ExceptionType.ArgumentException); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType) { return CreateInvalidHighSurrogateCharException(hi, exceptionType, 0, 0); } internal static Exception CreateInvalidHighSurrogateCharException(char hi, ExceptionType exceptionType, int lineNo, int linePos) { return CreateException(SR.Xml_InvalidSurrogateHighChar, ((uint)hi).ToString("X", CultureInfo.InvariantCulture), exceptionType, lineNo, linePos); } internal static Exception CreateInvalidCharException(char[] data, int length, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(string data, int invCharPos) { return CreateInvalidCharException(data, invCharPos, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(string data, int invCharPos, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, invCharPos), exceptionType, 0, invCharPos + 1); } internal static Exception CreateInvalidCharException(char invChar, char nextChar) { return CreateInvalidCharException(invChar, nextChar, ExceptionType.ArgumentException); } internal static Exception CreateInvalidCharException(char invChar, char nextChar, ExceptionType exceptionType) { return CreateException(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(invChar, nextChar), exceptionType); } internal static Exception CreateInvalidNameCharException(string name, int index, ExceptionType exceptionType) { return CreateException(index == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1); } } }
1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/RateAggregator.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.Diagnostics.Metrics { internal sealed class RateSumAggregator : Aggregator { private double _sum; public override void Update(double value) { lock (this) { _sum += value; } } public override IAggregationStatistics Collect() { lock (this) { RateStatistics? stats = new RateStatistics(_sum); _sum = 0; return stats; } } } internal sealed class RateAggregator : Aggregator { private double? _prevValue; private double _value; public override void Update(double value) { lock (this) { _value = value; } } public override IAggregationStatistics Collect() { lock (this) { double? delta = null; if (_prevValue.HasValue) { delta = _value - _prevValue.Value; } RateStatistics stats = new RateStatistics(delta); _prevValue = _value; return stats; } } } internal sealed class RateStatistics : IAggregationStatistics { public RateStatistics(double? delta) { Delta = delta; } public double? Delta { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Diagnostics.Metrics { internal sealed class RateSumAggregator : Aggregator { private double _sum; public override void Update(double value) { lock (this) { _sum += value; } } public override IAggregationStatistics Collect() { lock (this) { RateStatistics? stats = new RateStatistics(_sum); _sum = 0; return stats; } } } internal sealed class RateAggregator : Aggregator { private double? _prevValue; private double _value; public override void Update(double value) { lock (this) { _value = value; } } public override IAggregationStatistics Collect() { lock (this) { double? delta = null; if (_prevValue.HasValue) { delta = _value - _prevValue.Value; } RateStatistics stats = new RateStatistics(delta); _prevValue = _value; return stats; } } } internal sealed class RateStatistics : IAggregationStatistics { public RateStatistics(double? delta) { Delta = delta; } public double? Delta { get; } } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse2.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.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE2 hardware instructions via intrinsics /// </summary> [Intrinsic] [CLSCompliant(false)] public abstract class Sse2 : Sse { internal Sse2() { } public static new bool IsSupported { get => IsSupported; } [Intrinsic] public new abstract class X64 : Sse.X64 { internal X64() { } public static new bool IsSupported { get => IsSupported; } /// <summary> /// __int64 _mm_cvtsd_si64 (__m128d a) /// CVTSD2SI r64, xmm/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64(Vector128<double> value) => ConvertToInt64(value); /// <summary> /// __int64 _mm_cvtsi128_si64 (__m128i a) /// MOVQ reg/m64, xmm /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64(Vector128<long> value) => ConvertToInt64(value); /// <summary> /// __int64 _mm_cvtsi128_si64 (__m128i a) /// MOVQ reg/m64, xmm /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong ConvertToUInt64(Vector128<ulong> value) => ConvertToUInt64(value); /// <summary> /// __m128d _mm_cvtsi64_sd (__m128d a, __int64 b) /// CVTSI2SD xmm, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static Vector128<double> ConvertScalarToVector128Double(Vector128<double> upper, long value) => ConvertScalarToVector128Double(upper, value); /// <summary> /// __m128i _mm_cvtsi64_si128 (__int64 a) /// MOVQ xmm, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static Vector128<long> ConvertScalarToVector128Int64(long value) => ConvertScalarToVector128Int64(value); /// <summary> /// __m128i _mm_cvtsi64_si128 (__int64 a) /// MOVQ xmm, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static Vector128<ulong> ConvertScalarToVector128UInt64(ulong value) => ConvertScalarToVector128UInt64(value); /// <summary> /// __int64 _mm_cvttsd_si64 (__m128d a) /// CVTTSD2SI reg, xmm/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64WithTruncation(Vector128<double> value) => ConvertToInt64WithTruncation(value); /// <summary> /// void _mm_stream_si64(__int64 *p, __int64 a) /// MOVNTI m64, r64 /// This intrinisc is only available on 64-bit processes /// </summary> public static unsafe void StoreNonTemporal(long* address, long value) => StoreNonTemporal(address, value); /// <summary> /// void _mm_stream_si64(__int64 *p, __int64 a) /// MOVNTI m64, r64 /// This intrinisc is only available on 64-bit processes /// </summary> public static unsafe void StoreNonTemporal(ulong* address, ulong value) => StoreNonTemporal(address, value); } /// <summary> /// __m128i _mm_add_epi8 (__m128i a, __m128i b) /// PADDB xmm, xmm/m128 /// </summary> public static Vector128<byte> Add(Vector128<byte> left, Vector128<byte> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi8 (__m128i a, __m128i b) /// PADDB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Add(Vector128<sbyte> left, Vector128<sbyte> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi16 (__m128i a, __m128i b) /// PADDW xmm, xmm/m128 /// </summary> public static Vector128<short> Add(Vector128<short> left, Vector128<short> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi16 (__m128i a, __m128i b) /// PADDW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Add(Vector128<ushort> left, Vector128<ushort> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi32 (__m128i a, __m128i b) /// PADDD xmm, xmm/m128 /// </summary> public static Vector128<int> Add(Vector128<int> left, Vector128<int> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi32 (__m128i a, __m128i b) /// PADDD xmm, xmm/m128 /// </summary> public static Vector128<uint> Add(Vector128<uint> left, Vector128<uint> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi64 (__m128i a, __m128i b) /// PADDQ xmm, xmm/m128 /// </summary> public static Vector128<long> Add(Vector128<long> left, Vector128<long> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi64 (__m128i a, __m128i b) /// PADDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> Add(Vector128<ulong> left, Vector128<ulong> right) => Add(left, right); /// <summary> /// __m128d _mm_add_pd (__m128d a, __m128d b) /// ADDPD xmm, xmm/m128 /// </summary> public static Vector128<double> Add(Vector128<double> left, Vector128<double> right) => Add(left, right); /// <summary> /// __m128d _mm_add_sd (__m128d a, __m128d b) /// ADDSD xmm, xmm/m64 /// </summary> public static Vector128<double> AddScalar(Vector128<double> left, Vector128<double> right) => AddScalar(left, right); /// <summary> /// __m128i _mm_adds_epi8 (__m128i a, __m128i b) /// PADDSB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> AddSaturate(Vector128<sbyte> left, Vector128<sbyte> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_adds_epu8 (__m128i a, __m128i b) /// PADDUSB xmm, xmm/m128 /// </summary> public static Vector128<byte> AddSaturate(Vector128<byte> left, Vector128<byte> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_adds_epi16 (__m128i a, __m128i b) /// PADDSW xmm, xmm/m128 /// </summary> public static Vector128<short> AddSaturate(Vector128<short> left, Vector128<short> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_adds_epu16 (__m128i a, __m128i b) /// PADDUSW xmm, xmm/m128 /// </summary> public static Vector128<ushort> AddSaturate(Vector128<ushort> left, Vector128<ushort> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<byte> And(Vector128<byte> left, Vector128<byte> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<sbyte> And(Vector128<sbyte> left, Vector128<sbyte> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<short> And(Vector128<short> left, Vector128<short> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<ushort> And(Vector128<ushort> left, Vector128<ushort> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<int> And(Vector128<int> left, Vector128<int> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<uint> And(Vector128<uint> left, Vector128<uint> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<long> And(Vector128<long> left, Vector128<long> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<ulong> And(Vector128<ulong> left, Vector128<ulong> right) => And(left, right); /// <summary> /// __m128d _mm_and_pd (__m128d a, __m128d b) /// ANDPD xmm, xmm/m128 /// </summary> public static Vector128<double> And(Vector128<double> left, Vector128<double> right) => And(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<byte> AndNot(Vector128<byte> left, Vector128<byte> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<sbyte> AndNot(Vector128<sbyte> left, Vector128<sbyte> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<short> AndNot(Vector128<short> left, Vector128<short> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<ushort> AndNot(Vector128<ushort> left, Vector128<ushort> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<int> AndNot(Vector128<int> left, Vector128<int> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<uint> AndNot(Vector128<uint> left, Vector128<uint> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<long> AndNot(Vector128<long> left, Vector128<long> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<ulong> AndNot(Vector128<ulong> left, Vector128<ulong> right) => AndNot(left, right); /// <summary> /// __m128d _mm_andnot_pd (__m128d a, __m128d b) /// ADDNPD xmm, xmm/m128 /// </summary> public static Vector128<double> AndNot(Vector128<double> left, Vector128<double> right) => AndNot(left, right); /// <summary> /// __m128i _mm_avg_epu8 (__m128i a, __m128i b) /// PAVGB xmm, xmm/m128 /// </summary> public static Vector128<byte> Average(Vector128<byte> left, Vector128<byte> right) => Average(left, right); /// <summary> /// __m128i _mm_avg_epu16 (__m128i a, __m128i b) /// PAVGW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Average(Vector128<ushort> left, Vector128<ushort> right) => Average(left, right); /// <summary> /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) /// PCMPEQB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> CompareEqual(Vector128<sbyte> left, Vector128<sbyte> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) /// PCMPEQB xmm, xmm/m128 /// </summary> public static Vector128<byte> CompareEqual(Vector128<byte> left, Vector128<byte> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) /// PCMPEQW xmm, xmm/m128 /// </summary> public static Vector128<short> CompareEqual(Vector128<short> left, Vector128<short> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) /// PCMPEQW xmm, xmm/m128 /// </summary> public static Vector128<ushort> CompareEqual(Vector128<ushort> left, Vector128<ushort> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) /// PCMPEQD xmm, xmm/m128 /// </summary> public static Vector128<int> CompareEqual(Vector128<int> left, Vector128<int> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) /// PCMPEQD xmm, xmm/m128 /// </summary> public static Vector128<uint> CompareEqual(Vector128<uint> left, Vector128<uint> right) => CompareEqual(left, right); /// <summary> /// __m128d _mm_cmpeq_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(0) /// </summary> public static Vector128<double> CompareEqual(Vector128<double> left, Vector128<double> right) => CompareEqual(left, right); /// <summary> /// int _mm_comieq_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedEqual(left, right); /// <summary> /// int _mm_ucomieq_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedEqual(left, right); /// <summary> /// __m128d _mm_cmpeq_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(0) /// </summary> public static Vector128<double> CompareScalarEqual(Vector128<double> left, Vector128<double> right) => CompareScalarEqual(left, right); /// <summary> /// __m128i _mm_cmpgt_epi8 (__m128i a, __m128i b) /// PCMPGTB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> CompareGreaterThan(Vector128<sbyte> left, Vector128<sbyte> right) => CompareGreaterThan(left, right); /// <summary> /// __m128i _mm_cmpgt_epi16 (__m128i a, __m128i b) /// PCMPGTW xmm, xmm/m128 /// </summary> public static Vector128<short> CompareGreaterThan(Vector128<short> left, Vector128<short> right) => CompareGreaterThan(left, right); /// <summary> /// __m128i _mm_cmpgt_epi32 (__m128i a, __m128i b) /// PCMPGTD xmm, xmm/m128 /// </summary> public static Vector128<int> CompareGreaterThan(Vector128<int> left, Vector128<int> right) => CompareGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpgt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(1) with swapped operands /// </summary> public static Vector128<double> CompareGreaterThan(Vector128<double> left, Vector128<double> right) => CompareGreaterThan(left, right); /// <summary> /// int _mm_comigt_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedGreaterThan(left, right); /// <summary> /// int _mm_ucomigt_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpgt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(1) with swapped operands /// </summary> public static Vector128<double> CompareScalarGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpge_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(2) with swapped operands /// </summary> public static Vector128<double> CompareGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareGreaterThanOrEqual(left, right); /// <summary> /// int _mm_comige_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedGreaterThanOrEqual(left, right); /// <summary> /// int _mm_ucomige_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedGreaterThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpge_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(2) with swapped operands /// </summary> public static Vector128<double> CompareScalarGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarGreaterThanOrEqual(left, right); /// <summary> /// __m128i _mm_cmplt_epi8 (__m128i a, __m128i b) /// PCMPGTB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> CompareLessThan(Vector128<sbyte> left, Vector128<sbyte> right) => CompareLessThan(left, right); /// <summary> /// __m128i _mm_cmplt_epi16 (__m128i a, __m128i b) /// PCMPGTW xmm, xmm/m128 /// </summary> public static Vector128<short> CompareLessThan(Vector128<short> left, Vector128<short> right) => CompareLessThan(left, right); /// <summary> /// __m128i _mm_cmplt_epi32 (__m128i a, __m128i b) /// PCMPGTD xmm, xmm/m128 /// </summary> public static Vector128<int> CompareLessThan(Vector128<int> left, Vector128<int> right) => CompareLessThan(left, right); /// <summary> /// __m128d _mm_cmplt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(1) /// </summary> public static Vector128<double> CompareLessThan(Vector128<double> left, Vector128<double> right) => CompareLessThan(left, right); /// <summary> /// int _mm_comilt_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedLessThan(left, right); /// <summary> /// int _mm_ucomilt_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedLessThan(left, right); /// <summary> /// __m128d _mm_cmplt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(1) /// </summary> public static Vector128<double> CompareScalarLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarLessThan(left, right); /// <summary> /// __m128d _mm_cmple_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(2) /// </summary> public static Vector128<double> CompareLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareLessThanOrEqual(left, right); /// <summary> /// int _mm_comile_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedLessThanOrEqual(left, right); /// <summary> /// int _mm_ucomile_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmple_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(2) /// </summary> public static Vector128<double> CompareScalarLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpneq_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(4) /// </summary> public static Vector128<double> CompareNotEqual(Vector128<double> left, Vector128<double> right) => CompareNotEqual(left, right); /// <summary> /// int _mm_comineq_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedNotEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedNotEqual(left, right); /// <summary> /// int _mm_ucomineq_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedNotEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedNotEqual(left, right); /// <summary> /// __m128d _mm_cmpneq_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(4) /// </summary> public static Vector128<double> CompareScalarNotEqual(Vector128<double> left, Vector128<double> right) => CompareScalarNotEqual(left, right); /// <summary> /// __m128d _mm_cmpngt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(5) with swapped operands /// </summary> public static Vector128<double> CompareNotGreaterThan(Vector128<double> left, Vector128<double> right) => CompareNotGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpngt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(5) with swapped operands /// </summary> public static Vector128<double> CompareScalarNotGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarNotGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpnge_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(6) with swapped operands /// </summary> public static Vector128<double> CompareNotGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareNotGreaterThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpnge_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(6) with swapped operands /// </summary> public static Vector128<double> CompareScalarNotGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarNotGreaterThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpnlt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(5) /// </summary> public static Vector128<double> CompareNotLessThan(Vector128<double> left, Vector128<double> right) => CompareNotLessThan(left, right); /// <summary> /// __m128d _mm_cmpnlt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(5) /// </summary> public static Vector128<double> CompareScalarNotLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarNotLessThan(left, right); /// <summary> /// __m128d _mm_cmpnle_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(6) /// </summary> public static Vector128<double> CompareNotLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareNotLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpnle_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(6) /// </summary> public static Vector128<double> CompareScalarNotLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarNotLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpord_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(7) /// </summary> public static Vector128<double> CompareOrdered(Vector128<double> left, Vector128<double> right) => CompareOrdered(left, right); /// <summary> /// __m128d _mm_cmpord_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(7) /// </summary> public static Vector128<double> CompareScalarOrdered(Vector128<double> left, Vector128<double> right) => CompareScalarOrdered(left, right); /// <summary> /// __m128d _mm_cmpunord_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(3) /// </summary> public static Vector128<double> CompareUnordered(Vector128<double> left, Vector128<double> right) => CompareUnordered(left, right); /// <summary> /// __m128d _mm_cmpunord_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(3) /// </summary> public static Vector128<double> CompareScalarUnordered(Vector128<double> left, Vector128<double> right) => CompareScalarUnordered(left, right); /// <summary> /// __m128i _mm_cvtps_epi32 (__m128 a) /// CVTPS2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<float> value) => ConvertToVector128Int32(value); /// <summary> /// __m128i _mm_cvtpd_epi32 (__m128d a) /// CVTPD2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<double> value) => ConvertToVector128Int32(value); /// <summary> /// __m128 _mm_cvtepi32_ps (__m128i a) /// CVTDQ2PS xmm, xmm/m128 /// </summary> public static Vector128<float> ConvertToVector128Single(Vector128<int> value) => ConvertToVector128Single(value); /// <summary> /// __m128 _mm_cvtpd_ps (__m128d a) /// CVTPD2PS xmm, xmm/m128 /// </summary> public static Vector128<float> ConvertToVector128Single(Vector128<double> value) => ConvertToVector128Single(value); /// <summary> /// __m128d _mm_cvtepi32_pd (__m128i a) /// CVTDQ2PD xmm, xmm/m128 /// </summary> public static Vector128<double> ConvertToVector128Double(Vector128<int> value) => ConvertToVector128Double(value); /// <summary> /// __m128d _mm_cvtps_pd (__m128 a) /// CVTPS2PD xmm, xmm/m128 /// </summary> public static Vector128<double> ConvertToVector128Double(Vector128<float> value) => ConvertToVector128Double(value); /// <summary> /// int _mm_cvtsd_si32 (__m128d a) /// CVTSD2SI r32, xmm/m64 /// </summary> public static int ConvertToInt32(Vector128<double> value) => ConvertToInt32(value); /// <summary> /// int _mm_cvtsi128_si32 (__m128i a) /// MOVD reg/m32, xmm /// </summary> public static int ConvertToInt32(Vector128<int> value) => ConvertToInt32(value); /// <summary> /// int _mm_cvtsi128_si32 (__m128i a) /// MOVD reg/m32, xmm /// </summary> public static uint ConvertToUInt32(Vector128<uint> value) => ConvertToUInt32(value); /// <summary> /// __m128d _mm_cvtsi32_sd (__m128d a, int b) /// CVTSI2SD xmm, reg/m32 /// </summary> public static Vector128<double> ConvertScalarToVector128Double(Vector128<double> upper, int value) => ConvertScalarToVector128Double(upper, value); /// <summary> /// __m128d _mm_cvtss_sd (__m128d a, __m128 b) /// CVTSS2SD xmm, xmm/m32 /// </summary> public static Vector128<double> ConvertScalarToVector128Double(Vector128<double> upper, Vector128<float> value) => ConvertScalarToVector128Double(upper, value); /// <summary> /// __m128i _mm_cvtsi32_si128 (int a) /// MOVD xmm, reg/m32 /// </summary> public static Vector128<int> ConvertScalarToVector128Int32(int value) => ConvertScalarToVector128Int32(value); /// <summary> /// __m128 _mm_cvtsd_ss (__m128 a, __m128d b) /// CVTSD2SS xmm, xmm/m64 /// </summary> public static Vector128<float> ConvertScalarToVector128Single(Vector128<float> upper, Vector128<double> value) => ConvertScalarToVector128Single(upper, value); /// <summary> /// __m128i _mm_cvtsi32_si128 (int a) /// MOVD xmm, reg/m32 /// </summary> public static Vector128<uint> ConvertScalarToVector128UInt32(uint value) => ConvertScalarToVector128UInt32(value); /// <summary> /// __m128i _mm_cvttps_epi32 (__m128 a) /// CVTTPS2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32WithTruncation(Vector128<float> value) => ConvertToVector128Int32WithTruncation(value); /// <summary> /// __m128i _mm_cvttpd_epi32 (__m128d a) /// CVTTPD2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32WithTruncation(Vector128<double> value) => ConvertToVector128Int32WithTruncation(value); /// <summary> /// int _mm_cvttsd_si32 (__m128d a) /// CVTTSD2SI reg, xmm/m64 /// </summary> public static int ConvertToInt32WithTruncation(Vector128<double> value) => ConvertToInt32WithTruncation(value); /// <summary> /// __m128d _mm_div_pd (__m128d a, __m128d b) /// DIVPD xmm, xmm/m128 /// </summary> public static Vector128<double> Divide(Vector128<double> left, Vector128<double> right) => Divide(left, right); /// <summary> /// __m128d _mm_div_sd (__m128d a, __m128d b) /// DIVSD xmm, xmm/m64 /// </summary> public static Vector128<double> DivideScalar(Vector128<double> left, Vector128<double> right) => DivideScalar(left, right); /// <summary> /// int _mm_extract_epi16 (__m128i a, int immediate) /// PEXTRW reg, xmm, imm8 /// </summary> public static ushort Extract(Vector128<ushort> value, byte index) => Extract(value, index); /// <summary> /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) /// PINSRW xmm, reg/m16, imm8 /// </summary> public static Vector128<short> Insert(Vector128<short> value, short data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) /// PINSRW xmm, reg/m16, imm8 /// </summary> public static Vector128<ushort> Insert(Vector128<ushort> value, ushort data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<sbyte> LoadVector128(sbyte* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<byte> LoadVector128(byte* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<short> LoadVector128(short* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<ushort> LoadVector128(ushort* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<int> LoadVector128(int* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<uint> LoadVector128(uint* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<long> LoadVector128(long* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<ulong> LoadVector128(ulong* address) => LoadVector128(address); /// <summary> /// __m128d _mm_loadu_pd (double const* mem_address) /// MOVUPD xmm, m128 /// </summary> public static unsafe Vector128<double> LoadVector128(double* address) => LoadVector128(address); /// <summary> /// __m128d _mm_load_sd (double const* mem_address) /// MOVSD xmm, m64 /// </summary> public static unsafe Vector128<double> LoadScalarVector128(double* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<sbyte> LoadAlignedVector128(sbyte* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<byte> LoadAlignedVector128(byte* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<short> LoadAlignedVector128(short* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<ushort> LoadAlignedVector128(ushort* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<int> LoadAlignedVector128(int* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<uint> LoadAlignedVector128(uint* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<long> LoadAlignedVector128(long* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<ulong> LoadAlignedVector128(ulong* address) => LoadAlignedVector128(address); /// <summary> /// __m128d _mm_load_pd (double const* mem_address) /// MOVAPD xmm, m128 /// </summary> public static unsafe Vector128<double> LoadAlignedVector128(double* address) => LoadAlignedVector128(address); /// <summary> /// void _mm_lfence(void) /// LFENCE /// </summary> public static void LoadFence() => LoadFence(); /// <summary> /// __m128d _mm_loadh_pd (__m128d a, double const* mem_addr) /// MOVHPD xmm, m64 /// </summary> public static unsafe Vector128<double> LoadHigh(Vector128<double> lower, double* address) => LoadHigh(lower, address); /// <summary> /// __m128d _mm_loadl_pd (__m128d a, double const* mem_addr) /// MOVLPD xmm, m64 /// </summary> public static unsafe Vector128<double> LoadLow(Vector128<double> upper, double* address) => LoadLow(upper, address); /// <summary> /// __m128i _mm_loadu_si32 (void const* mem_addr) /// MOVD xmm, reg/m32 /// </summary> public static unsafe Vector128<int> LoadScalarVector128(int* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_loadu_si32 (void const* mem_addr) /// MOVD xmm, reg/m32 /// </summary> public static unsafe Vector128<uint> LoadScalarVector128(uint* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) /// MOVQ xmm, reg/m64 /// </summary> public static unsafe Vector128<long> LoadScalarVector128(long* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) /// MOVQ xmm, reg/m64 /// </summary> public static unsafe Vector128<ulong> LoadScalarVector128(ulong* address) => LoadScalarVector128(address); /// <summary> /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) /// MASKMOVDQU xmm, xmm /// </summary> public static unsafe void MaskMove(Vector128<sbyte> source, Vector128<sbyte> mask, sbyte* address) => MaskMove(source, mask, address); /// <summary> /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) /// MASKMOVDQU xmm, xmm /// </summary> public static unsafe void MaskMove(Vector128<byte> source, Vector128<byte> mask, byte* address) => MaskMove(source, mask, address); /// <summary> /// __m128i _mm_max_epu8 (__m128i a, __m128i b) /// PMAXUB xmm, xmm/m128 /// </summary> public static Vector128<byte> Max(Vector128<byte> left, Vector128<byte> right) => Max(left, right); /// <summary> /// __m128i _mm_max_epi16 (__m128i a, __m128i b) /// PMAXSW xmm, xmm/m128 /// </summary> public static Vector128<short> Max(Vector128<short> left, Vector128<short> right) => Max(left, right); /// <summary> /// __m128d _mm_max_pd (__m128d a, __m128d b) /// MAXPD xmm, xmm/m128 /// </summary> public static Vector128<double> Max(Vector128<double> left, Vector128<double> right) => Max(left, right); /// <summary> /// __m128d _mm_max_sd (__m128d a, __m128d b) /// MAXSD xmm, xmm/m64 /// </summary> public static Vector128<double> MaxScalar(Vector128<double> left, Vector128<double> right) => MaxScalar(left, right); /// <summary> /// void _mm_mfence(void) /// MFENCE /// </summary> public static void MemoryFence() => MemoryFence(); /// <summary> /// __m128i _mm_min_epu8 (__m128i a, __m128i b) /// PMINUB xmm, xmm/m128 /// </summary> public static Vector128<byte> Min(Vector128<byte> left, Vector128<byte> right) => Min(left, right); /// <summary> /// __m128i _mm_min_epi16 (__m128i a, __m128i b) /// PMINSW xmm, xmm/m128 /// </summary> public static Vector128<short> Min(Vector128<short> left, Vector128<short> right) => Min(left, right); /// <summary> /// __m128d _mm_min_pd (__m128d a, __m128d b) /// MINPD xmm, xmm/m128 /// </summary> public static Vector128<double> Min(Vector128<double> left, Vector128<double> right) => Min(left, right); /// <summary> /// __m128d _mm_min_sd (__m128d a, __m128d b) /// MINSD xmm, xmm/m64 /// </summary> public static Vector128<double> MinScalar(Vector128<double> left, Vector128<double> right) => MinScalar(left, right); /// <summary> /// __m128d _mm_move_sd (__m128d a, __m128d b) /// MOVSD xmm, xmm /// </summary> public static Vector128<double> MoveScalar(Vector128<double> upper, Vector128<double> value) => MoveScalar(upper, value); /// <summary> /// int _mm_movemask_epi8 (__m128i a) /// PMOVMSKB reg, xmm /// </summary> public static int MoveMask(Vector128<sbyte> value) => MoveMask(value); /// <summary> /// int _mm_movemask_epi8 (__m128i a) /// PMOVMSKB reg, xmm /// </summary> public static int MoveMask(Vector128<byte> value) => MoveMask(value); /// <summary> /// int _mm_movemask_pd (__m128d a) /// MOVMSKPD reg, xmm /// </summary> public static int MoveMask(Vector128<double> value) => MoveMask(value); /// <summary> /// __m128i _mm_move_epi64 (__m128i a) /// MOVQ xmm, xmm /// </summary> public static Vector128<long> MoveScalar(Vector128<long> value) => MoveScalar(value); /// <summary> /// __m128i _mm_move_epi64 (__m128i a) /// MOVQ xmm, xmm /// </summary> public static Vector128<ulong> MoveScalar(Vector128<ulong> value) => MoveScalar(value); /// <summary> /// __m128i _mm_mul_epu32 (__m128i a, __m128i b) /// PMULUDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> Multiply(Vector128<uint> left, Vector128<uint> right) => Multiply(left, right); /// <summary> /// __m128d _mm_mul_pd (__m128d a, __m128d b) /// MULPD xmm, xmm/m128 /// </summary> public static Vector128<double> Multiply(Vector128<double> left, Vector128<double> right) => Multiply(left, right); /// <summary> /// __m128d _mm_mul_sd (__m128d a, __m128d b) /// MULSD xmm, xmm/m64 /// </summary> public static Vector128<double> MultiplyScalar(Vector128<double> left, Vector128<double> right) => MultiplyScalar(left, right); /// <summary> /// __m128i _mm_mulhi_epi16 (__m128i a, __m128i b) /// PMULHW xmm, xmm/m128 /// </summary> public static Vector128<short> MultiplyHigh(Vector128<short> left, Vector128<short> right) => MultiplyHigh(left, right); /// <summary> /// __m128i _mm_mulhi_epu16 (__m128i a, __m128i b) /// PMULHUW xmm, xmm/m128 /// </summary> public static Vector128<ushort> MultiplyHigh(Vector128<ushort> left, Vector128<ushort> right) => MultiplyHigh(left, right); /// <summary> /// __m128i _mm_madd_epi16 (__m128i a, __m128i b) /// PMADDWD xmm, xmm/m128 /// </summary> public static Vector128<int> MultiplyAddAdjacent(Vector128<short> left, Vector128<short> right) => MultiplyAddAdjacent(left, right); /// <summary> /// __m128i _mm_mullo_epi16 (__m128i a, __m128i b) /// PMULLW xmm, xmm/m128 /// </summary> public static Vector128<short> MultiplyLow(Vector128<short> left, Vector128<short> right) => MultiplyLow(left, right); /// <summary> /// __m128i _mm_mullo_epi16 (__m128i a, __m128i b) /// PMULLW xmm, xmm/m128 /// </summary> public static Vector128<ushort> MultiplyLow(Vector128<ushort> left, Vector128<ushort> right) => MultiplyLow(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<byte> Or(Vector128<byte> left, Vector128<byte> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Or(Vector128<sbyte> left, Vector128<sbyte> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<short> Or(Vector128<short> left, Vector128<short> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<ushort> Or(Vector128<ushort> left, Vector128<ushort> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<int> Or(Vector128<int> left, Vector128<int> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<uint> Or(Vector128<uint> left, Vector128<uint> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<long> Or(Vector128<long> left, Vector128<long> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<ulong> Or(Vector128<ulong> left, Vector128<ulong> right) => Or(left, right); /// <summary> /// __m128d _mm_or_pd (__m128d a, __m128d b) /// ORPD xmm, xmm/m128 /// </summary> public static Vector128<double> Or(Vector128<double> left, Vector128<double> right) => Or(left, right); /// <summary> /// __m128i _mm_packs_epi16 (__m128i a, __m128i b) /// PACKSSWB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> PackSignedSaturate(Vector128<short> left, Vector128<short> right) => PackSignedSaturate(left, right); /// <summary> /// __m128i _mm_packs_epi32 (__m128i a, __m128i b) /// PACKSSDW xmm, xmm/m128 /// </summary> public static Vector128<short> PackSignedSaturate(Vector128<int> left, Vector128<int> right) => PackSignedSaturate(left, right); /// <summary> /// __m128i _mm_packus_epi16 (__m128i a, __m128i b) /// PACKUSWB xmm, xmm/m128 /// </summary> public static Vector128<byte> PackUnsignedSaturate(Vector128<short> left, Vector128<short> right) => PackUnsignedSaturate(left, right); /// <summary> /// __m128i _mm_sad_epu8 (__m128i a, __m128i b) /// PSADBW xmm, xmm/m128 /// </summary> public static Vector128<ushort> SumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right) => SumAbsoluteDifferences(left, right); /// <summary> /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) /// PSHUFD xmm, xmm/m128, imm8 /// </summary> public static Vector128<int> Shuffle(Vector128<int> value, byte control) => Shuffle(value, control); /// <summary> /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) /// PSHUFD xmm, xmm/m128, imm8 /// </summary> public static Vector128<uint> Shuffle(Vector128<uint> value, byte control) => Shuffle(value, control); /// <summary> /// __m128d _mm_shuffle_pd (__m128d a, __m128d b, int immediate) /// SHUFPD xmm, xmm/m128, imm8 /// </summary> public static Vector128<double> Shuffle(Vector128<double> left, Vector128<double> right, byte control) => Shuffle(left, right, control); /// <summary> /// __m128i _mm_shufflehi_epi16 (__m128i a, int immediate) /// PSHUFHW xmm, xmm/m128, imm8 /// </summary> public static Vector128<short> ShuffleHigh(Vector128<short> value, byte control) => ShuffleHigh(value, control); /// <summary> /// __m128i _mm_shufflehi_epi16 (__m128i a, int control) /// PSHUFHW xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> ShuffleHigh(Vector128<ushort> value, byte control) => ShuffleHigh(value, control); /// <summary> /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) /// PSHUFLW xmm, xmm/m128, imm8 /// </summary> public static Vector128<short> ShuffleLow(Vector128<short> value, byte control) => ShuffleLow(value, control); /// <summary> /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) /// PSHUFLW xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> ShuffleLow(Vector128<ushort> value, byte control) => ShuffleLow(value, control); /// <summary> /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) /// PSLLW xmm, xmm/m128 /// </summary> public static Vector128<short> ShiftLeftLogical(Vector128<short> value, Vector128<short> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) /// PSLLW xmm, xmm/m128 /// </summary> public static Vector128<ushort> ShiftLeftLogical(Vector128<ushort> value, Vector128<ushort> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) /// PSLLD xmm, xmm/m128 /// </summary> public static Vector128<int> ShiftLeftLogical(Vector128<int> value, Vector128<int> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) /// PSLLD xmm, xmm/m128 /// </summary> public static Vector128<uint> ShiftLeftLogical(Vector128<uint> value, Vector128<uint> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) /// PSLLQ xmm, xmm/m128 /// </summary> public static Vector128<long> ShiftLeftLogical(Vector128<long> value, Vector128<long> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) /// PSLLQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> ShiftLeftLogical(Vector128<ulong> value, Vector128<ulong> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi16 (__m128i a, int immediate) /// PSLLW xmm, imm8 /// </summary> public static Vector128<short> ShiftLeftLogical(Vector128<short> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi16 (__m128i a, int immediate) /// PSLLW xmm, imm8 /// </summary> public static Vector128<ushort> ShiftLeftLogical(Vector128<ushort> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi32 (__m128i a, int immediate) /// PSLLD xmm, imm8 /// </summary> public static Vector128<int> ShiftLeftLogical(Vector128<int> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi32 (__m128i a, int immediate) /// PSLLD xmm, imm8 /// </summary> public static Vector128<uint> ShiftLeftLogical(Vector128<uint> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi64 (__m128i a, int immediate) /// PSLLQ xmm, imm8 /// </summary> public static Vector128<long> ShiftLeftLogical(Vector128<long> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi64 (__m128i a, int immediate) /// PSLLQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftLeftLogical(Vector128<ulong> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<sbyte> ShiftLeftLogical128BitLane(Vector128<sbyte> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<byte> ShiftLeftLogical128BitLane(Vector128<byte> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<short> ShiftLeftLogical128BitLane(Vector128<short> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<ushort> ShiftLeftLogical128BitLane(Vector128<ushort> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<int> ShiftLeftLogical128BitLane(Vector128<int> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<uint> ShiftLeftLogical128BitLane(Vector128<uint> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<long> ShiftLeftLogical128BitLane(Vector128<long> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftLeftLogical128BitLane(Vector128<ulong> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_sra_epi16 (__m128i a, __m128i count) /// PSRAW xmm, xmm/m128 /// </summary> public static Vector128<short> ShiftRightArithmetic(Vector128<short> value, Vector128<short> count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_sra_epi32 (__m128i a, __m128i count) /// PSRAD xmm, xmm/m128 /// </summary> public static Vector128<int> ShiftRightArithmetic(Vector128<int> value, Vector128<int> count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_srai_epi16 (__m128i a, int immediate) /// PSRAW xmm, imm8 /// </summary> public static Vector128<short> ShiftRightArithmetic(Vector128<short> value, byte count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_srai_epi32 (__m128i a, int immediate) /// PSRAD xmm, imm8 /// </summary> public static Vector128<int> ShiftRightArithmetic(Vector128<int> value, byte count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) /// PSRLW xmm, xmm/m128 /// </summary> public static Vector128<short> ShiftRightLogical(Vector128<short> value, Vector128<short> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) /// PSRLW xmm, xmm/m128 /// </summary> public static Vector128<ushort> ShiftRightLogical(Vector128<ushort> value, Vector128<ushort> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) /// PSRLD xmm, xmm/m128 /// </summary> public static Vector128<int> ShiftRightLogical(Vector128<int> value, Vector128<int> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) /// PSRLD xmm, xmm/m128 /// </summary> public static Vector128<uint> ShiftRightLogical(Vector128<uint> value, Vector128<uint> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) /// PSRLQ xmm, xmm/m128 /// </summary> public static Vector128<long> ShiftRightLogical(Vector128<long> value, Vector128<long> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) /// PSRLQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> ShiftRightLogical(Vector128<ulong> value, Vector128<ulong> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi16 (__m128i a, int immediate) /// PSRLW xmm, imm8 /// </summary> public static Vector128<short> ShiftRightLogical(Vector128<short> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi16 (__m128i a, int immediate) /// PSRLW xmm, imm8 /// </summary> public static Vector128<ushort> ShiftRightLogical(Vector128<ushort> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi32 (__m128i a, int immediate) /// PSRLD xmm, imm8 /// </summary> public static Vector128<int> ShiftRightLogical(Vector128<int> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi32 (__m128i a, int immediate) /// PSRLD xmm, imm8 /// </summary> public static Vector128<uint> ShiftRightLogical(Vector128<uint> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi64 (__m128i a, int immediate) /// PSRLQ xmm, imm8 /// </summary> public static Vector128<long> ShiftRightLogical(Vector128<long> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi64 (__m128i a, int immediate) /// PSRLQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftRightLogical(Vector128<ulong> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<sbyte> ShiftRightLogical128BitLane(Vector128<sbyte> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<byte> ShiftRightLogical128BitLane(Vector128<byte> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<short> ShiftRightLogical128BitLane(Vector128<short> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<ushort> ShiftRightLogical128BitLane(Vector128<ushort> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<int> ShiftRightLogical128BitLane(Vector128<int> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<uint> ShiftRightLogical128BitLane(Vector128<uint> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<long> ShiftRightLogical128BitLane(Vector128<long> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftRightLogical128BitLane(Vector128<ulong> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128d _mm_sqrt_pd (__m128d a) /// SQRTPD xmm, xmm/m128 /// </summary> public static Vector128<double> Sqrt(Vector128<double> value) => Sqrt(value); /// <summary> /// __m128d _mm_sqrt_sd (__m128d a) /// SQRTSD xmm, xmm/64 /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> SqrtScalar(Vector128<double> value) => SqrtScalar(value); /// <summary> /// __m128d _mm_sqrt_sd (__m128d a, __m128d b) /// SQRTSD xmm, xmm/64 /// </summary> public static Vector128<double> SqrtScalar(Vector128<double> upper, Vector128<double> value) => SqrtScalar(upper, value); /// <summary> /// void _mm_store_sd (double* mem_addr, __m128d a) /// MOVSD m64, xmm /// </summary> public static unsafe void StoreScalar(double* address, Vector128<double> source) => StoreScalar(address, source); /// <summary> /// void _mm_storeu_si32 (void* mem_addr, __m128i a) /// MOVD m32, xmm /// </summary> public static unsafe void StoreScalar(int* address, Vector128<int> source) => StoreScalar(address, source); /// <summary> /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) /// MOVQ m64, xmm /// </summary> public static unsafe void StoreScalar(long* address, Vector128<long> source) => StoreScalar(address, source); /// <summary> /// void _mm_storeu_si32 (void* mem_addr, __m128i a) /// MOVD m32, xmm /// </summary> public static unsafe void StoreScalar(uint* address, Vector128<uint> source) => StoreScalar(address, source); /// <summary> /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) /// MOVQ m64, xmm /// </summary> public static unsafe void StoreScalar(ulong* address, Vector128<ulong> source) => StoreScalar(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(sbyte* address, Vector128<sbyte> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(byte* address, Vector128<byte> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(short* address, Vector128<short> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(ushort* address, Vector128<ushort> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(int* address, Vector128<int> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(uint* address, Vector128<uint> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(long* address, Vector128<long> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(ulong* address, Vector128<ulong> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_pd (double* mem_addr, __m128d a) /// MOVAPD m128, xmm /// </summary> public static unsafe void StoreAligned(double* address, Vector128<double> source) => StoreAligned(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector128<sbyte> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(byte* address, Vector128<byte> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(short* address, Vector128<short> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector128<ushort> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(int* address, Vector128<int> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(uint* address, Vector128<uint> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(long* address, Vector128<long> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector128<ulong> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_pd (double* mem_addr, __m128d a) /// MOVNTPD m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(double* address, Vector128<double> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(sbyte* address, Vector128<sbyte> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(byte* address, Vector128<byte> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(short* address, Vector128<short> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(ushort* address, Vector128<ushort> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(int* address, Vector128<int> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(uint* address, Vector128<uint> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(long* address, Vector128<long> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(ulong* address, Vector128<ulong> source) => Store(address, source); /// <summary> /// void _mm_storeu_pd (double* mem_addr, __m128d a) /// MOVUPD m128, xmm /// </summary> public static unsafe void Store(double* address, Vector128<double> source) => Store(address, source); /// <summary> /// void _mm_storeh_pd (double* mem_addr, __m128d a) /// MOVHPD m64, xmm /// </summary> public static unsafe void StoreHigh(double* address, Vector128<double> source) => StoreHigh(address, source); /// <summary> /// void _mm_storel_pd (double* mem_addr, __m128d a) /// MOVLPD m64, xmm /// </summary> public static unsafe void StoreLow(double* address, Vector128<double> source) => StoreLow(address, source); /// <summary> /// void _mm_stream_si32(int *p, int a) /// MOVNTI m32, r32 /// </summary> public static unsafe void StoreNonTemporal(int* address, int value) => StoreNonTemporal(address, value); /// <summary> /// void _mm_stream_si32(int *p, int a) /// MOVNTI m32, r32 /// </summary> public static unsafe void StoreNonTemporal(uint* address, uint value) => StoreNonTemporal(address, value); /// <summary> /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) /// PSUBB xmm, xmm/m128 /// </summary> public static Vector128<byte> Subtract(Vector128<byte> left, Vector128<byte> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) /// PSUBB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Subtract(Vector128<sbyte> left, Vector128<sbyte> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) /// PSUBW xmm, xmm/m128 /// </summary> public static Vector128<short> Subtract(Vector128<short> left, Vector128<short> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) /// PSUBW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Subtract(Vector128<ushort> left, Vector128<ushort> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) /// PSUBD xmm, xmm/m128 /// </summary> public static Vector128<int> Subtract(Vector128<int> left, Vector128<int> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) /// PSUBD xmm, xmm/m128 /// </summary> public static Vector128<uint> Subtract(Vector128<uint> left, Vector128<uint> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) /// PSUBQ xmm, xmm/m128 /// </summary> public static Vector128<long> Subtract(Vector128<long> left, Vector128<long> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) /// PSUBQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> Subtract(Vector128<ulong> left, Vector128<ulong> right) => Subtract(left, right); /// <summary> /// __m128d _mm_sub_pd (__m128d a, __m128d b) /// SUBPD xmm, xmm/m128 /// </summary> public static Vector128<double> Subtract(Vector128<double> left, Vector128<double> right) => Subtract(left, right); /// <summary> /// __m128d _mm_sub_sd (__m128d a, __m128d b) /// SUBSD xmm, xmm/m64 /// </summary> public static Vector128<double> SubtractScalar(Vector128<double> left, Vector128<double> right) => SubtractScalar(left, right); /// <summary> /// __m128i _mm_subs_epi8 (__m128i a, __m128i b) /// PSUBSB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> SubtractSaturate(Vector128<sbyte> left, Vector128<sbyte> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_subs_epi16 (__m128i a, __m128i b) /// PSUBSW xmm, xmm/m128 /// </summary> public static Vector128<short> SubtractSaturate(Vector128<short> left, Vector128<short> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_subs_epu8 (__m128i a, __m128i b) /// PSUBUSB xmm, xmm/m128 /// </summary> public static Vector128<byte> SubtractSaturate(Vector128<byte> left, Vector128<byte> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_subs_epu16 (__m128i a, __m128i b) /// PSUBUSW xmm, xmm/m128 /// </summary> public static Vector128<ushort> SubtractSaturate(Vector128<ushort> left, Vector128<ushort> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) /// PUNPCKHBW xmm, xmm/m128 /// </summary> public static Vector128<byte> UnpackHigh(Vector128<byte> left, Vector128<byte> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) /// PUNPCKHBW xmm, xmm/m128 /// </summary> public static Vector128<sbyte> UnpackHigh(Vector128<sbyte> left, Vector128<sbyte> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) /// PUNPCKHWD xmm, xmm/m128 /// </summary> public static Vector128<short> UnpackHigh(Vector128<short> left, Vector128<short> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) /// PUNPCKHWD xmm, xmm/m128 /// </summary> public static Vector128<ushort> UnpackHigh(Vector128<ushort> left, Vector128<ushort> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) /// PUNPCKHDQ xmm, xmm/m128 /// </summary> public static Vector128<int> UnpackHigh(Vector128<int> left, Vector128<int> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) /// PUNPCKHDQ xmm, xmm/m128 /// </summary> public static Vector128<uint> UnpackHigh(Vector128<uint> left, Vector128<uint> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) /// PUNPCKHQDQ xmm, xmm/m128 /// </summary> public static Vector128<long> UnpackHigh(Vector128<long> left, Vector128<long> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) /// PUNPCKHQDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> UnpackHigh(Vector128<ulong> left, Vector128<ulong> right) => UnpackHigh(left, right); /// <summary> /// __m128d _mm_unpackhi_pd (__m128d a, __m128d b) /// UNPCKHPD xmm, xmm/m128 /// </summary> public static Vector128<double> UnpackHigh(Vector128<double> left, Vector128<double> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) /// PUNPCKLBW xmm, xmm/m128 /// </summary> public static Vector128<byte> UnpackLow(Vector128<byte> left, Vector128<byte> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) /// PUNPCKLBW xmm, xmm/m128 /// </summary> public static Vector128<sbyte> UnpackLow(Vector128<sbyte> left, Vector128<sbyte> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) /// PUNPCKLWD xmm, xmm/m128 /// </summary> public static Vector128<short> UnpackLow(Vector128<short> left, Vector128<short> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) /// PUNPCKLWD xmm, xmm/m128 /// </summary> public static Vector128<ushort> UnpackLow(Vector128<ushort> left, Vector128<ushort> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) /// PUNPCKLDQ xmm, xmm/m128 /// </summary> public static Vector128<int> UnpackLow(Vector128<int> left, Vector128<int> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) /// PUNPCKLDQ xmm, xmm/m128 /// </summary> public static Vector128<uint> UnpackLow(Vector128<uint> left, Vector128<uint> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) /// PUNPCKLQDQ xmm, xmm/m128 /// </summary> public static Vector128<long> UnpackLow(Vector128<long> left, Vector128<long> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) /// PUNPCKLQDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> UnpackLow(Vector128<ulong> left, Vector128<ulong> right) => UnpackLow(left, right); /// <summary> /// __m128d _mm_unpacklo_pd (__m128d a, __m128d b) /// UNPCKLPD xmm, xmm/m128 /// </summary> public static Vector128<double> UnpackLow(Vector128<double> left, Vector128<double> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<byte> Xor(Vector128<byte> left, Vector128<byte> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Xor(Vector128<sbyte> left, Vector128<sbyte> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<short> Xor(Vector128<short> left, Vector128<short> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<ushort> Xor(Vector128<ushort> left, Vector128<ushort> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<int> Xor(Vector128<int> left, Vector128<int> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<uint> Xor(Vector128<uint> left, Vector128<uint> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<long> Xor(Vector128<long> left, Vector128<long> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<ulong> Xor(Vector128<ulong> left, Vector128<ulong> right) => Xor(left, right); /// <summary> /// __m128d _mm_xor_pd (__m128d a, __m128d b) /// XORPD xmm, xmm/m128 /// </summary> public static Vector128<double> Xor(Vector128<double> left, Vector128<double> right) => Xor(left, right); } }
// 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.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE2 hardware instructions via intrinsics /// </summary> [Intrinsic] [CLSCompliant(false)] public abstract class Sse2 : Sse { internal Sse2() { } public static new bool IsSupported { get => IsSupported; } [Intrinsic] public new abstract class X64 : Sse.X64 { internal X64() { } public static new bool IsSupported { get => IsSupported; } /// <summary> /// __int64 _mm_cvtsd_si64 (__m128d a) /// CVTSD2SI r64, xmm/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64(Vector128<double> value) => ConvertToInt64(value); /// <summary> /// __int64 _mm_cvtsi128_si64 (__m128i a) /// MOVQ reg/m64, xmm /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64(Vector128<long> value) => ConvertToInt64(value); /// <summary> /// __int64 _mm_cvtsi128_si64 (__m128i a) /// MOVQ reg/m64, xmm /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong ConvertToUInt64(Vector128<ulong> value) => ConvertToUInt64(value); /// <summary> /// __m128d _mm_cvtsi64_sd (__m128d a, __int64 b) /// CVTSI2SD xmm, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static Vector128<double> ConvertScalarToVector128Double(Vector128<double> upper, long value) => ConvertScalarToVector128Double(upper, value); /// <summary> /// __m128i _mm_cvtsi64_si128 (__int64 a) /// MOVQ xmm, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static Vector128<long> ConvertScalarToVector128Int64(long value) => ConvertScalarToVector128Int64(value); /// <summary> /// __m128i _mm_cvtsi64_si128 (__int64 a) /// MOVQ xmm, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static Vector128<ulong> ConvertScalarToVector128UInt64(ulong value) => ConvertScalarToVector128UInt64(value); /// <summary> /// __int64 _mm_cvttsd_si64 (__m128d a) /// CVTTSD2SI reg, xmm/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64WithTruncation(Vector128<double> value) => ConvertToInt64WithTruncation(value); /// <summary> /// void _mm_stream_si64(__int64 *p, __int64 a) /// MOVNTI m64, r64 /// This intrinisc is only available on 64-bit processes /// </summary> public static unsafe void StoreNonTemporal(long* address, long value) => StoreNonTemporal(address, value); /// <summary> /// void _mm_stream_si64(__int64 *p, __int64 a) /// MOVNTI m64, r64 /// This intrinisc is only available on 64-bit processes /// </summary> public static unsafe void StoreNonTemporal(ulong* address, ulong value) => StoreNonTemporal(address, value); } /// <summary> /// __m128i _mm_add_epi8 (__m128i a, __m128i b) /// PADDB xmm, xmm/m128 /// </summary> public static Vector128<byte> Add(Vector128<byte> left, Vector128<byte> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi8 (__m128i a, __m128i b) /// PADDB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Add(Vector128<sbyte> left, Vector128<sbyte> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi16 (__m128i a, __m128i b) /// PADDW xmm, xmm/m128 /// </summary> public static Vector128<short> Add(Vector128<short> left, Vector128<short> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi16 (__m128i a, __m128i b) /// PADDW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Add(Vector128<ushort> left, Vector128<ushort> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi32 (__m128i a, __m128i b) /// PADDD xmm, xmm/m128 /// </summary> public static Vector128<int> Add(Vector128<int> left, Vector128<int> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi32 (__m128i a, __m128i b) /// PADDD xmm, xmm/m128 /// </summary> public static Vector128<uint> Add(Vector128<uint> left, Vector128<uint> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi64 (__m128i a, __m128i b) /// PADDQ xmm, xmm/m128 /// </summary> public static Vector128<long> Add(Vector128<long> left, Vector128<long> right) => Add(left, right); /// <summary> /// __m128i _mm_add_epi64 (__m128i a, __m128i b) /// PADDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> Add(Vector128<ulong> left, Vector128<ulong> right) => Add(left, right); /// <summary> /// __m128d _mm_add_pd (__m128d a, __m128d b) /// ADDPD xmm, xmm/m128 /// </summary> public static Vector128<double> Add(Vector128<double> left, Vector128<double> right) => Add(left, right); /// <summary> /// __m128d _mm_add_sd (__m128d a, __m128d b) /// ADDSD xmm, xmm/m64 /// </summary> public static Vector128<double> AddScalar(Vector128<double> left, Vector128<double> right) => AddScalar(left, right); /// <summary> /// __m128i _mm_adds_epi8 (__m128i a, __m128i b) /// PADDSB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> AddSaturate(Vector128<sbyte> left, Vector128<sbyte> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_adds_epu8 (__m128i a, __m128i b) /// PADDUSB xmm, xmm/m128 /// </summary> public static Vector128<byte> AddSaturate(Vector128<byte> left, Vector128<byte> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_adds_epi16 (__m128i a, __m128i b) /// PADDSW xmm, xmm/m128 /// </summary> public static Vector128<short> AddSaturate(Vector128<short> left, Vector128<short> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_adds_epu16 (__m128i a, __m128i b) /// PADDUSW xmm, xmm/m128 /// </summary> public static Vector128<ushort> AddSaturate(Vector128<ushort> left, Vector128<ushort> right) => AddSaturate(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<byte> And(Vector128<byte> left, Vector128<byte> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<sbyte> And(Vector128<sbyte> left, Vector128<sbyte> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<short> And(Vector128<short> left, Vector128<short> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<ushort> And(Vector128<ushort> left, Vector128<ushort> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<int> And(Vector128<int> left, Vector128<int> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<uint> And(Vector128<uint> left, Vector128<uint> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<long> And(Vector128<long> left, Vector128<long> right) => And(left, right); /// <summary> /// __m128i _mm_and_si128 (__m128i a, __m128i b) /// PAND xmm, xmm/m128 /// </summary> public static Vector128<ulong> And(Vector128<ulong> left, Vector128<ulong> right) => And(left, right); /// <summary> /// __m128d _mm_and_pd (__m128d a, __m128d b) /// ANDPD xmm, xmm/m128 /// </summary> public static Vector128<double> And(Vector128<double> left, Vector128<double> right) => And(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<byte> AndNot(Vector128<byte> left, Vector128<byte> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<sbyte> AndNot(Vector128<sbyte> left, Vector128<sbyte> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<short> AndNot(Vector128<short> left, Vector128<short> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<ushort> AndNot(Vector128<ushort> left, Vector128<ushort> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<int> AndNot(Vector128<int> left, Vector128<int> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<uint> AndNot(Vector128<uint> left, Vector128<uint> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<long> AndNot(Vector128<long> left, Vector128<long> right) => AndNot(left, right); /// <summary> /// __m128i _mm_andnot_si128 (__m128i a, __m128i b) /// PANDN xmm, xmm/m128 /// </summary> public static Vector128<ulong> AndNot(Vector128<ulong> left, Vector128<ulong> right) => AndNot(left, right); /// <summary> /// __m128d _mm_andnot_pd (__m128d a, __m128d b) /// ADDNPD xmm, xmm/m128 /// </summary> public static Vector128<double> AndNot(Vector128<double> left, Vector128<double> right) => AndNot(left, right); /// <summary> /// __m128i _mm_avg_epu8 (__m128i a, __m128i b) /// PAVGB xmm, xmm/m128 /// </summary> public static Vector128<byte> Average(Vector128<byte> left, Vector128<byte> right) => Average(left, right); /// <summary> /// __m128i _mm_avg_epu16 (__m128i a, __m128i b) /// PAVGW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Average(Vector128<ushort> left, Vector128<ushort> right) => Average(left, right); /// <summary> /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) /// PCMPEQB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> CompareEqual(Vector128<sbyte> left, Vector128<sbyte> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) /// PCMPEQB xmm, xmm/m128 /// </summary> public static Vector128<byte> CompareEqual(Vector128<byte> left, Vector128<byte> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) /// PCMPEQW xmm, xmm/m128 /// </summary> public static Vector128<short> CompareEqual(Vector128<short> left, Vector128<short> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) /// PCMPEQW xmm, xmm/m128 /// </summary> public static Vector128<ushort> CompareEqual(Vector128<ushort> left, Vector128<ushort> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) /// PCMPEQD xmm, xmm/m128 /// </summary> public static Vector128<int> CompareEqual(Vector128<int> left, Vector128<int> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b) /// PCMPEQD xmm, xmm/m128 /// </summary> public static Vector128<uint> CompareEqual(Vector128<uint> left, Vector128<uint> right) => CompareEqual(left, right); /// <summary> /// __m128d _mm_cmpeq_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(0) /// </summary> public static Vector128<double> CompareEqual(Vector128<double> left, Vector128<double> right) => CompareEqual(left, right); /// <summary> /// int _mm_comieq_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedEqual(left, right); /// <summary> /// int _mm_ucomieq_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedEqual(left, right); /// <summary> /// __m128d _mm_cmpeq_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(0) /// </summary> public static Vector128<double> CompareScalarEqual(Vector128<double> left, Vector128<double> right) => CompareScalarEqual(left, right); /// <summary> /// __m128i _mm_cmpgt_epi8 (__m128i a, __m128i b) /// PCMPGTB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> CompareGreaterThan(Vector128<sbyte> left, Vector128<sbyte> right) => CompareGreaterThan(left, right); /// <summary> /// __m128i _mm_cmpgt_epi16 (__m128i a, __m128i b) /// PCMPGTW xmm, xmm/m128 /// </summary> public static Vector128<short> CompareGreaterThan(Vector128<short> left, Vector128<short> right) => CompareGreaterThan(left, right); /// <summary> /// __m128i _mm_cmpgt_epi32 (__m128i a, __m128i b) /// PCMPGTD xmm, xmm/m128 /// </summary> public static Vector128<int> CompareGreaterThan(Vector128<int> left, Vector128<int> right) => CompareGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpgt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(1) with swapped operands /// </summary> public static Vector128<double> CompareGreaterThan(Vector128<double> left, Vector128<double> right) => CompareGreaterThan(left, right); /// <summary> /// int _mm_comigt_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedGreaterThan(left, right); /// <summary> /// int _mm_ucomigt_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpgt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(1) with swapped operands /// </summary> public static Vector128<double> CompareScalarGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpge_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(2) with swapped operands /// </summary> public static Vector128<double> CompareGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareGreaterThanOrEqual(left, right); /// <summary> /// int _mm_comige_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedGreaterThanOrEqual(left, right); /// <summary> /// int _mm_ucomige_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedGreaterThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpge_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(2) with swapped operands /// </summary> public static Vector128<double> CompareScalarGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarGreaterThanOrEqual(left, right); /// <summary> /// __m128i _mm_cmplt_epi8 (__m128i a, __m128i b) /// PCMPGTB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> CompareLessThan(Vector128<sbyte> left, Vector128<sbyte> right) => CompareLessThan(left, right); /// <summary> /// __m128i _mm_cmplt_epi16 (__m128i a, __m128i b) /// PCMPGTW xmm, xmm/m128 /// </summary> public static Vector128<short> CompareLessThan(Vector128<short> left, Vector128<short> right) => CompareLessThan(left, right); /// <summary> /// __m128i _mm_cmplt_epi32 (__m128i a, __m128i b) /// PCMPGTD xmm, xmm/m128 /// </summary> public static Vector128<int> CompareLessThan(Vector128<int> left, Vector128<int> right) => CompareLessThan(left, right); /// <summary> /// __m128d _mm_cmplt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(1) /// </summary> public static Vector128<double> CompareLessThan(Vector128<double> left, Vector128<double> right) => CompareLessThan(left, right); /// <summary> /// int _mm_comilt_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedLessThan(left, right); /// <summary> /// int _mm_ucomilt_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedLessThan(left, right); /// <summary> /// __m128d _mm_cmplt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(1) /// </summary> public static Vector128<double> CompareScalarLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarLessThan(left, right); /// <summary> /// __m128d _mm_cmple_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(2) /// </summary> public static Vector128<double> CompareLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareLessThanOrEqual(left, right); /// <summary> /// int _mm_comile_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedLessThanOrEqual(left, right); /// <summary> /// int _mm_ucomile_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmple_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(2) /// </summary> public static Vector128<double> CompareScalarLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpneq_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(4) /// </summary> public static Vector128<double> CompareNotEqual(Vector128<double> left, Vector128<double> right) => CompareNotEqual(left, right); /// <summary> /// int _mm_comineq_sd (__m128d a, __m128d b) /// COMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarOrderedNotEqual(Vector128<double> left, Vector128<double> right) => CompareScalarOrderedNotEqual(left, right); /// <summary> /// int _mm_ucomineq_sd (__m128d a, __m128d b) /// UCOMISD xmm, xmm/m64 /// </summary> public static bool CompareScalarUnorderedNotEqual(Vector128<double> left, Vector128<double> right) => CompareScalarUnorderedNotEqual(left, right); /// <summary> /// __m128d _mm_cmpneq_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(4) /// </summary> public static Vector128<double> CompareScalarNotEqual(Vector128<double> left, Vector128<double> right) => CompareScalarNotEqual(left, right); /// <summary> /// __m128d _mm_cmpngt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(5) with swapped operands /// </summary> public static Vector128<double> CompareNotGreaterThan(Vector128<double> left, Vector128<double> right) => CompareNotGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpngt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(5) with swapped operands /// </summary> public static Vector128<double> CompareScalarNotGreaterThan(Vector128<double> left, Vector128<double> right) => CompareScalarNotGreaterThan(left, right); /// <summary> /// __m128d _mm_cmpnge_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(6) with swapped operands /// </summary> public static Vector128<double> CompareNotGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareNotGreaterThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpnge_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(6) with swapped operands /// </summary> public static Vector128<double> CompareScalarNotGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarNotGreaterThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpnlt_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(5) /// </summary> public static Vector128<double> CompareNotLessThan(Vector128<double> left, Vector128<double> right) => CompareNotLessThan(left, right); /// <summary> /// __m128d _mm_cmpnlt_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(5) /// </summary> public static Vector128<double> CompareScalarNotLessThan(Vector128<double> left, Vector128<double> right) => CompareScalarNotLessThan(left, right); /// <summary> /// __m128d _mm_cmpnle_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(6) /// </summary> public static Vector128<double> CompareNotLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareNotLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpnle_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(6) /// </summary> public static Vector128<double> CompareScalarNotLessThanOrEqual(Vector128<double> left, Vector128<double> right) => CompareScalarNotLessThanOrEqual(left, right); /// <summary> /// __m128d _mm_cmpord_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(7) /// </summary> public static Vector128<double> CompareOrdered(Vector128<double> left, Vector128<double> right) => CompareOrdered(left, right); /// <summary> /// __m128d _mm_cmpord_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(7) /// </summary> public static Vector128<double> CompareScalarOrdered(Vector128<double> left, Vector128<double> right) => CompareScalarOrdered(left, right); /// <summary> /// __m128d _mm_cmpunord_pd (__m128d a, __m128d b) /// CMPPD xmm, xmm/m128, imm8(3) /// </summary> public static Vector128<double> CompareUnordered(Vector128<double> left, Vector128<double> right) => CompareUnordered(left, right); /// <summary> /// __m128d _mm_cmpunord_sd (__m128d a, __m128d b) /// CMPSD xmm, xmm/m64, imm8(3) /// </summary> public static Vector128<double> CompareScalarUnordered(Vector128<double> left, Vector128<double> right) => CompareScalarUnordered(left, right); /// <summary> /// __m128i _mm_cvtps_epi32 (__m128 a) /// CVTPS2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<float> value) => ConvertToVector128Int32(value); /// <summary> /// __m128i _mm_cvtpd_epi32 (__m128d a) /// CVTPD2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<double> value) => ConvertToVector128Int32(value); /// <summary> /// __m128 _mm_cvtepi32_ps (__m128i a) /// CVTDQ2PS xmm, xmm/m128 /// </summary> public static Vector128<float> ConvertToVector128Single(Vector128<int> value) => ConvertToVector128Single(value); /// <summary> /// __m128 _mm_cvtpd_ps (__m128d a) /// CVTPD2PS xmm, xmm/m128 /// </summary> public static Vector128<float> ConvertToVector128Single(Vector128<double> value) => ConvertToVector128Single(value); /// <summary> /// __m128d _mm_cvtepi32_pd (__m128i a) /// CVTDQ2PD xmm, xmm/m128 /// </summary> public static Vector128<double> ConvertToVector128Double(Vector128<int> value) => ConvertToVector128Double(value); /// <summary> /// __m128d _mm_cvtps_pd (__m128 a) /// CVTPS2PD xmm, xmm/m128 /// </summary> public static Vector128<double> ConvertToVector128Double(Vector128<float> value) => ConvertToVector128Double(value); /// <summary> /// int _mm_cvtsd_si32 (__m128d a) /// CVTSD2SI r32, xmm/m64 /// </summary> public static int ConvertToInt32(Vector128<double> value) => ConvertToInt32(value); /// <summary> /// int _mm_cvtsi128_si32 (__m128i a) /// MOVD reg/m32, xmm /// </summary> public static int ConvertToInt32(Vector128<int> value) => ConvertToInt32(value); /// <summary> /// int _mm_cvtsi128_si32 (__m128i a) /// MOVD reg/m32, xmm /// </summary> public static uint ConvertToUInt32(Vector128<uint> value) => ConvertToUInt32(value); /// <summary> /// __m128d _mm_cvtsi32_sd (__m128d a, int b) /// CVTSI2SD xmm, reg/m32 /// </summary> public static Vector128<double> ConvertScalarToVector128Double(Vector128<double> upper, int value) => ConvertScalarToVector128Double(upper, value); /// <summary> /// __m128d _mm_cvtss_sd (__m128d a, __m128 b) /// CVTSS2SD xmm, xmm/m32 /// </summary> public static Vector128<double> ConvertScalarToVector128Double(Vector128<double> upper, Vector128<float> value) => ConvertScalarToVector128Double(upper, value); /// <summary> /// __m128i _mm_cvtsi32_si128 (int a) /// MOVD xmm, reg/m32 /// </summary> public static Vector128<int> ConvertScalarToVector128Int32(int value) => ConvertScalarToVector128Int32(value); /// <summary> /// __m128 _mm_cvtsd_ss (__m128 a, __m128d b) /// CVTSD2SS xmm, xmm/m64 /// </summary> public static Vector128<float> ConvertScalarToVector128Single(Vector128<float> upper, Vector128<double> value) => ConvertScalarToVector128Single(upper, value); /// <summary> /// __m128i _mm_cvtsi32_si128 (int a) /// MOVD xmm, reg/m32 /// </summary> public static Vector128<uint> ConvertScalarToVector128UInt32(uint value) => ConvertScalarToVector128UInt32(value); /// <summary> /// __m128i _mm_cvttps_epi32 (__m128 a) /// CVTTPS2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32WithTruncation(Vector128<float> value) => ConvertToVector128Int32WithTruncation(value); /// <summary> /// __m128i _mm_cvttpd_epi32 (__m128d a) /// CVTTPD2DQ xmm, xmm/m128 /// </summary> public static Vector128<int> ConvertToVector128Int32WithTruncation(Vector128<double> value) => ConvertToVector128Int32WithTruncation(value); /// <summary> /// int _mm_cvttsd_si32 (__m128d a) /// CVTTSD2SI reg, xmm/m64 /// </summary> public static int ConvertToInt32WithTruncation(Vector128<double> value) => ConvertToInt32WithTruncation(value); /// <summary> /// __m128d _mm_div_pd (__m128d a, __m128d b) /// DIVPD xmm, xmm/m128 /// </summary> public static Vector128<double> Divide(Vector128<double> left, Vector128<double> right) => Divide(left, right); /// <summary> /// __m128d _mm_div_sd (__m128d a, __m128d b) /// DIVSD xmm, xmm/m64 /// </summary> public static Vector128<double> DivideScalar(Vector128<double> left, Vector128<double> right) => DivideScalar(left, right); /// <summary> /// int _mm_extract_epi16 (__m128i a, int immediate) /// PEXTRW reg, xmm, imm8 /// </summary> public static ushort Extract(Vector128<ushort> value, byte index) => Extract(value, index); /// <summary> /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) /// PINSRW xmm, reg/m16, imm8 /// </summary> public static Vector128<short> Insert(Vector128<short> value, short data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate) /// PINSRW xmm, reg/m16, imm8 /// </summary> public static Vector128<ushort> Insert(Vector128<ushort> value, ushort data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<sbyte> LoadVector128(sbyte* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<byte> LoadVector128(byte* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<short> LoadVector128(short* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<ushort> LoadVector128(ushort* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<int> LoadVector128(int* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<uint> LoadVector128(uint* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<long> LoadVector128(long* address) => LoadVector128(address); /// <summary> /// __m128i _mm_loadu_si128 (__m128i const* mem_address) /// MOVDQU xmm, m128 /// </summary> public static unsafe Vector128<ulong> LoadVector128(ulong* address) => LoadVector128(address); /// <summary> /// __m128d _mm_loadu_pd (double const* mem_address) /// MOVUPD xmm, m128 /// </summary> public static unsafe Vector128<double> LoadVector128(double* address) => LoadVector128(address); /// <summary> /// __m128d _mm_load_sd (double const* mem_address) /// MOVSD xmm, m64 /// </summary> public static unsafe Vector128<double> LoadScalarVector128(double* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<sbyte> LoadAlignedVector128(sbyte* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<byte> LoadAlignedVector128(byte* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<short> LoadAlignedVector128(short* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<ushort> LoadAlignedVector128(ushort* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<int> LoadAlignedVector128(int* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<uint> LoadAlignedVector128(uint* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<long> LoadAlignedVector128(long* address) => LoadAlignedVector128(address); /// <summary> /// __m128i _mm_load_si128 (__m128i const* mem_address) /// MOVDQA xmm, m128 /// </summary> public static unsafe Vector128<ulong> LoadAlignedVector128(ulong* address) => LoadAlignedVector128(address); /// <summary> /// __m128d _mm_load_pd (double const* mem_address) /// MOVAPD xmm, m128 /// </summary> public static unsafe Vector128<double> LoadAlignedVector128(double* address) => LoadAlignedVector128(address); /// <summary> /// void _mm_lfence(void) /// LFENCE /// </summary> public static void LoadFence() => LoadFence(); /// <summary> /// __m128d _mm_loadh_pd (__m128d a, double const* mem_addr) /// MOVHPD xmm, m64 /// </summary> public static unsafe Vector128<double> LoadHigh(Vector128<double> lower, double* address) => LoadHigh(lower, address); /// <summary> /// __m128d _mm_loadl_pd (__m128d a, double const* mem_addr) /// MOVLPD xmm, m64 /// </summary> public static unsafe Vector128<double> LoadLow(Vector128<double> upper, double* address) => LoadLow(upper, address); /// <summary> /// __m128i _mm_loadu_si32 (void const* mem_addr) /// MOVD xmm, reg/m32 /// </summary> public static unsafe Vector128<int> LoadScalarVector128(int* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_loadu_si32 (void const* mem_addr) /// MOVD xmm, reg/m32 /// </summary> public static unsafe Vector128<uint> LoadScalarVector128(uint* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) /// MOVQ xmm, reg/m64 /// </summary> public static unsafe Vector128<long> LoadScalarVector128(long* address) => LoadScalarVector128(address); /// <summary> /// __m128i _mm_loadl_epi64 (__m128i const* mem_addr) /// MOVQ xmm, reg/m64 /// </summary> public static unsafe Vector128<ulong> LoadScalarVector128(ulong* address) => LoadScalarVector128(address); /// <summary> /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) /// MASKMOVDQU xmm, xmm /// </summary> public static unsafe void MaskMove(Vector128<sbyte> source, Vector128<sbyte> mask, sbyte* address) => MaskMove(source, mask, address); /// <summary> /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address) /// MASKMOVDQU xmm, xmm /// </summary> public static unsafe void MaskMove(Vector128<byte> source, Vector128<byte> mask, byte* address) => MaskMove(source, mask, address); /// <summary> /// __m128i _mm_max_epu8 (__m128i a, __m128i b) /// PMAXUB xmm, xmm/m128 /// </summary> public static Vector128<byte> Max(Vector128<byte> left, Vector128<byte> right) => Max(left, right); /// <summary> /// __m128i _mm_max_epi16 (__m128i a, __m128i b) /// PMAXSW xmm, xmm/m128 /// </summary> public static Vector128<short> Max(Vector128<short> left, Vector128<short> right) => Max(left, right); /// <summary> /// __m128d _mm_max_pd (__m128d a, __m128d b) /// MAXPD xmm, xmm/m128 /// </summary> public static Vector128<double> Max(Vector128<double> left, Vector128<double> right) => Max(left, right); /// <summary> /// __m128d _mm_max_sd (__m128d a, __m128d b) /// MAXSD xmm, xmm/m64 /// </summary> public static Vector128<double> MaxScalar(Vector128<double> left, Vector128<double> right) => MaxScalar(left, right); /// <summary> /// void _mm_mfence(void) /// MFENCE /// </summary> public static void MemoryFence() => MemoryFence(); /// <summary> /// __m128i _mm_min_epu8 (__m128i a, __m128i b) /// PMINUB xmm, xmm/m128 /// </summary> public static Vector128<byte> Min(Vector128<byte> left, Vector128<byte> right) => Min(left, right); /// <summary> /// __m128i _mm_min_epi16 (__m128i a, __m128i b) /// PMINSW xmm, xmm/m128 /// </summary> public static Vector128<short> Min(Vector128<short> left, Vector128<short> right) => Min(left, right); /// <summary> /// __m128d _mm_min_pd (__m128d a, __m128d b) /// MINPD xmm, xmm/m128 /// </summary> public static Vector128<double> Min(Vector128<double> left, Vector128<double> right) => Min(left, right); /// <summary> /// __m128d _mm_min_sd (__m128d a, __m128d b) /// MINSD xmm, xmm/m64 /// </summary> public static Vector128<double> MinScalar(Vector128<double> left, Vector128<double> right) => MinScalar(left, right); /// <summary> /// __m128d _mm_move_sd (__m128d a, __m128d b) /// MOVSD xmm, xmm /// </summary> public static Vector128<double> MoveScalar(Vector128<double> upper, Vector128<double> value) => MoveScalar(upper, value); /// <summary> /// int _mm_movemask_epi8 (__m128i a) /// PMOVMSKB reg, xmm /// </summary> public static int MoveMask(Vector128<sbyte> value) => MoveMask(value); /// <summary> /// int _mm_movemask_epi8 (__m128i a) /// PMOVMSKB reg, xmm /// </summary> public static int MoveMask(Vector128<byte> value) => MoveMask(value); /// <summary> /// int _mm_movemask_pd (__m128d a) /// MOVMSKPD reg, xmm /// </summary> public static int MoveMask(Vector128<double> value) => MoveMask(value); /// <summary> /// __m128i _mm_move_epi64 (__m128i a) /// MOVQ xmm, xmm /// </summary> public static Vector128<long> MoveScalar(Vector128<long> value) => MoveScalar(value); /// <summary> /// __m128i _mm_move_epi64 (__m128i a) /// MOVQ xmm, xmm /// </summary> public static Vector128<ulong> MoveScalar(Vector128<ulong> value) => MoveScalar(value); /// <summary> /// __m128i _mm_mul_epu32 (__m128i a, __m128i b) /// PMULUDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> Multiply(Vector128<uint> left, Vector128<uint> right) => Multiply(left, right); /// <summary> /// __m128d _mm_mul_pd (__m128d a, __m128d b) /// MULPD xmm, xmm/m128 /// </summary> public static Vector128<double> Multiply(Vector128<double> left, Vector128<double> right) => Multiply(left, right); /// <summary> /// __m128d _mm_mul_sd (__m128d a, __m128d b) /// MULSD xmm, xmm/m64 /// </summary> public static Vector128<double> MultiplyScalar(Vector128<double> left, Vector128<double> right) => MultiplyScalar(left, right); /// <summary> /// __m128i _mm_mulhi_epi16 (__m128i a, __m128i b) /// PMULHW xmm, xmm/m128 /// </summary> public static Vector128<short> MultiplyHigh(Vector128<short> left, Vector128<short> right) => MultiplyHigh(left, right); /// <summary> /// __m128i _mm_mulhi_epu16 (__m128i a, __m128i b) /// PMULHUW xmm, xmm/m128 /// </summary> public static Vector128<ushort> MultiplyHigh(Vector128<ushort> left, Vector128<ushort> right) => MultiplyHigh(left, right); /// <summary> /// __m128i _mm_madd_epi16 (__m128i a, __m128i b) /// PMADDWD xmm, xmm/m128 /// </summary> public static Vector128<int> MultiplyAddAdjacent(Vector128<short> left, Vector128<short> right) => MultiplyAddAdjacent(left, right); /// <summary> /// __m128i _mm_mullo_epi16 (__m128i a, __m128i b) /// PMULLW xmm, xmm/m128 /// </summary> public static Vector128<short> MultiplyLow(Vector128<short> left, Vector128<short> right) => MultiplyLow(left, right); /// <summary> /// __m128i _mm_mullo_epi16 (__m128i a, __m128i b) /// PMULLW xmm, xmm/m128 /// </summary> public static Vector128<ushort> MultiplyLow(Vector128<ushort> left, Vector128<ushort> right) => MultiplyLow(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<byte> Or(Vector128<byte> left, Vector128<byte> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Or(Vector128<sbyte> left, Vector128<sbyte> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<short> Or(Vector128<short> left, Vector128<short> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<ushort> Or(Vector128<ushort> left, Vector128<ushort> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<int> Or(Vector128<int> left, Vector128<int> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<uint> Or(Vector128<uint> left, Vector128<uint> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<long> Or(Vector128<long> left, Vector128<long> right) => Or(left, right); /// <summary> /// __m128i _mm_or_si128 (__m128i a, __m128i b) /// POR xmm, xmm/m128 /// </summary> public static Vector128<ulong> Or(Vector128<ulong> left, Vector128<ulong> right) => Or(left, right); /// <summary> /// __m128d _mm_or_pd (__m128d a, __m128d b) /// ORPD xmm, xmm/m128 /// </summary> public static Vector128<double> Or(Vector128<double> left, Vector128<double> right) => Or(left, right); /// <summary> /// __m128i _mm_packs_epi16 (__m128i a, __m128i b) /// PACKSSWB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> PackSignedSaturate(Vector128<short> left, Vector128<short> right) => PackSignedSaturate(left, right); /// <summary> /// __m128i _mm_packs_epi32 (__m128i a, __m128i b) /// PACKSSDW xmm, xmm/m128 /// </summary> public static Vector128<short> PackSignedSaturate(Vector128<int> left, Vector128<int> right) => PackSignedSaturate(left, right); /// <summary> /// __m128i _mm_packus_epi16 (__m128i a, __m128i b) /// PACKUSWB xmm, xmm/m128 /// </summary> public static Vector128<byte> PackUnsignedSaturate(Vector128<short> left, Vector128<short> right) => PackUnsignedSaturate(left, right); /// <summary> /// __m128i _mm_sad_epu8 (__m128i a, __m128i b) /// PSADBW xmm, xmm/m128 /// </summary> public static Vector128<ushort> SumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right) => SumAbsoluteDifferences(left, right); /// <summary> /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) /// PSHUFD xmm, xmm/m128, imm8 /// </summary> public static Vector128<int> Shuffle(Vector128<int> value, byte control) => Shuffle(value, control); /// <summary> /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate) /// PSHUFD xmm, xmm/m128, imm8 /// </summary> public static Vector128<uint> Shuffle(Vector128<uint> value, byte control) => Shuffle(value, control); /// <summary> /// __m128d _mm_shuffle_pd (__m128d a, __m128d b, int immediate) /// SHUFPD xmm, xmm/m128, imm8 /// </summary> public static Vector128<double> Shuffle(Vector128<double> left, Vector128<double> right, byte control) => Shuffle(left, right, control); /// <summary> /// __m128i _mm_shufflehi_epi16 (__m128i a, int immediate) /// PSHUFHW xmm, xmm/m128, imm8 /// </summary> public static Vector128<short> ShuffleHigh(Vector128<short> value, byte control) => ShuffleHigh(value, control); /// <summary> /// __m128i _mm_shufflehi_epi16 (__m128i a, int control) /// PSHUFHW xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> ShuffleHigh(Vector128<ushort> value, byte control) => ShuffleHigh(value, control); /// <summary> /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) /// PSHUFLW xmm, xmm/m128, imm8 /// </summary> public static Vector128<short> ShuffleLow(Vector128<short> value, byte control) => ShuffleLow(value, control); /// <summary> /// __m128i _mm_shufflelo_epi16 (__m128i a, int control) /// PSHUFLW xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> ShuffleLow(Vector128<ushort> value, byte control) => ShuffleLow(value, control); /// <summary> /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) /// PSLLW xmm, xmm/m128 /// </summary> public static Vector128<short> ShiftLeftLogical(Vector128<short> value, Vector128<short> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi16 (__m128i a, __m128i count) /// PSLLW xmm, xmm/m128 /// </summary> public static Vector128<ushort> ShiftLeftLogical(Vector128<ushort> value, Vector128<ushort> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) /// PSLLD xmm, xmm/m128 /// </summary> public static Vector128<int> ShiftLeftLogical(Vector128<int> value, Vector128<int> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi32 (__m128i a, __m128i count) /// PSLLD xmm, xmm/m128 /// </summary> public static Vector128<uint> ShiftLeftLogical(Vector128<uint> value, Vector128<uint> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) /// PSLLQ xmm, xmm/m128 /// </summary> public static Vector128<long> ShiftLeftLogical(Vector128<long> value, Vector128<long> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_sll_epi64 (__m128i a, __m128i count) /// PSLLQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> ShiftLeftLogical(Vector128<ulong> value, Vector128<ulong> count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi16 (__m128i a, int immediate) /// PSLLW xmm, imm8 /// </summary> public static Vector128<short> ShiftLeftLogical(Vector128<short> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi16 (__m128i a, int immediate) /// PSLLW xmm, imm8 /// </summary> public static Vector128<ushort> ShiftLeftLogical(Vector128<ushort> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi32 (__m128i a, int immediate) /// PSLLD xmm, imm8 /// </summary> public static Vector128<int> ShiftLeftLogical(Vector128<int> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi32 (__m128i a, int immediate) /// PSLLD xmm, imm8 /// </summary> public static Vector128<uint> ShiftLeftLogical(Vector128<uint> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi64 (__m128i a, int immediate) /// PSLLQ xmm, imm8 /// </summary> public static Vector128<long> ShiftLeftLogical(Vector128<long> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_slli_epi64 (__m128i a, int immediate) /// PSLLQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftLeftLogical(Vector128<ulong> value, byte count) => ShiftLeftLogical(value, count); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<sbyte> ShiftLeftLogical128BitLane(Vector128<sbyte> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<byte> ShiftLeftLogical128BitLane(Vector128<byte> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<short> ShiftLeftLogical128BitLane(Vector128<short> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<ushort> ShiftLeftLogical128BitLane(Vector128<ushort> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<int> ShiftLeftLogical128BitLane(Vector128<int> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<uint> ShiftLeftLogical128BitLane(Vector128<uint> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<long> ShiftLeftLogical128BitLane(Vector128<long> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bslli_si128 (__m128i a, int imm8) /// PSLLDQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftLeftLogical128BitLane(Vector128<ulong> value, byte numBytes) => ShiftLeftLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_sra_epi16 (__m128i a, __m128i count) /// PSRAW xmm, xmm/m128 /// </summary> public static Vector128<short> ShiftRightArithmetic(Vector128<short> value, Vector128<short> count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_sra_epi32 (__m128i a, __m128i count) /// PSRAD xmm, xmm/m128 /// </summary> public static Vector128<int> ShiftRightArithmetic(Vector128<int> value, Vector128<int> count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_srai_epi16 (__m128i a, int immediate) /// PSRAW xmm, imm8 /// </summary> public static Vector128<short> ShiftRightArithmetic(Vector128<short> value, byte count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_srai_epi32 (__m128i a, int immediate) /// PSRAD xmm, imm8 /// </summary> public static Vector128<int> ShiftRightArithmetic(Vector128<int> value, byte count) => ShiftRightArithmetic(value, count); /// <summary> /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) /// PSRLW xmm, xmm/m128 /// </summary> public static Vector128<short> ShiftRightLogical(Vector128<short> value, Vector128<short> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi16 (__m128i a, __m128i count) /// PSRLW xmm, xmm/m128 /// </summary> public static Vector128<ushort> ShiftRightLogical(Vector128<ushort> value, Vector128<ushort> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) /// PSRLD xmm, xmm/m128 /// </summary> public static Vector128<int> ShiftRightLogical(Vector128<int> value, Vector128<int> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi32 (__m128i a, __m128i count) /// PSRLD xmm, xmm/m128 /// </summary> public static Vector128<uint> ShiftRightLogical(Vector128<uint> value, Vector128<uint> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) /// PSRLQ xmm, xmm/m128 /// </summary> public static Vector128<long> ShiftRightLogical(Vector128<long> value, Vector128<long> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srl_epi64 (__m128i a, __m128i count) /// PSRLQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> ShiftRightLogical(Vector128<ulong> value, Vector128<ulong> count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi16 (__m128i a, int immediate) /// PSRLW xmm, imm8 /// </summary> public static Vector128<short> ShiftRightLogical(Vector128<short> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi16 (__m128i a, int immediate) /// PSRLW xmm, imm8 /// </summary> public static Vector128<ushort> ShiftRightLogical(Vector128<ushort> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi32 (__m128i a, int immediate) /// PSRLD xmm, imm8 /// </summary> public static Vector128<int> ShiftRightLogical(Vector128<int> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi32 (__m128i a, int immediate) /// PSRLD xmm, imm8 /// </summary> public static Vector128<uint> ShiftRightLogical(Vector128<uint> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi64 (__m128i a, int immediate) /// PSRLQ xmm, imm8 /// </summary> public static Vector128<long> ShiftRightLogical(Vector128<long> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_srli_epi64 (__m128i a, int immediate) /// PSRLQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftRightLogical(Vector128<ulong> value, byte count) => ShiftRightLogical(value, count); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<sbyte> ShiftRightLogical128BitLane(Vector128<sbyte> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<byte> ShiftRightLogical128BitLane(Vector128<byte> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<short> ShiftRightLogical128BitLane(Vector128<short> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<ushort> ShiftRightLogical128BitLane(Vector128<ushort> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<int> ShiftRightLogical128BitLane(Vector128<int> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<uint> ShiftRightLogical128BitLane(Vector128<uint> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<long> ShiftRightLogical128BitLane(Vector128<long> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128i _mm_bsrli_si128 (__m128i a, int imm8) /// PSRLDQ xmm, imm8 /// </summary> public static Vector128<ulong> ShiftRightLogical128BitLane(Vector128<ulong> value, byte numBytes) => ShiftRightLogical128BitLane(value, numBytes); /// <summary> /// __m128d _mm_sqrt_pd (__m128d a) /// SQRTPD xmm, xmm/m128 /// </summary> public static Vector128<double> Sqrt(Vector128<double> value) => Sqrt(value); /// <summary> /// __m128d _mm_sqrt_sd (__m128d a) /// SQRTSD xmm, xmm/64 /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> SqrtScalar(Vector128<double> value) => SqrtScalar(value); /// <summary> /// __m128d _mm_sqrt_sd (__m128d a, __m128d b) /// SQRTSD xmm, xmm/64 /// </summary> public static Vector128<double> SqrtScalar(Vector128<double> upper, Vector128<double> value) => SqrtScalar(upper, value); /// <summary> /// void _mm_store_sd (double* mem_addr, __m128d a) /// MOVSD m64, xmm /// </summary> public static unsafe void StoreScalar(double* address, Vector128<double> source) => StoreScalar(address, source); /// <summary> /// void _mm_storeu_si32 (void* mem_addr, __m128i a) /// MOVD m32, xmm /// </summary> public static unsafe void StoreScalar(int* address, Vector128<int> source) => StoreScalar(address, source); /// <summary> /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) /// MOVQ m64, xmm /// </summary> public static unsafe void StoreScalar(long* address, Vector128<long> source) => StoreScalar(address, source); /// <summary> /// void _mm_storeu_si32 (void* mem_addr, __m128i a) /// MOVD m32, xmm /// </summary> public static unsafe void StoreScalar(uint* address, Vector128<uint> source) => StoreScalar(address, source); /// <summary> /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a) /// MOVQ m64, xmm /// </summary> public static unsafe void StoreScalar(ulong* address, Vector128<ulong> source) => StoreScalar(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(sbyte* address, Vector128<sbyte> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(byte* address, Vector128<byte> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(short* address, Vector128<short> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(ushort* address, Vector128<ushort> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(int* address, Vector128<int> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(uint* address, Vector128<uint> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(long* address, Vector128<long> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_si128 (__m128i* mem_addr, __m128i a) /// MOVDQA m128, xmm /// </summary> public static unsafe void StoreAligned(ulong* address, Vector128<ulong> source) => StoreAligned(address, source); /// <summary> /// void _mm_store_pd (double* mem_addr, __m128d a) /// MOVAPD m128, xmm /// </summary> public static unsafe void StoreAligned(double* address, Vector128<double> source) => StoreAligned(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector128<sbyte> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(byte* address, Vector128<byte> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(short* address, Vector128<short> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector128<ushort> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(int* address, Vector128<int> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(uint* address, Vector128<uint> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(long* address, Vector128<long> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a) /// MOVNTDQ m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector128<ulong> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_stream_pd (double* mem_addr, __m128d a) /// MOVNTPD m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(double* address, Vector128<double> source) => StoreAlignedNonTemporal(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(sbyte* address, Vector128<sbyte> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(byte* address, Vector128<byte> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(short* address, Vector128<short> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(ushort* address, Vector128<ushort> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(int* address, Vector128<int> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(uint* address, Vector128<uint> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(long* address, Vector128<long> source) => Store(address, source); /// <summary> /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a) /// MOVDQU m128, xmm /// </summary> public static unsafe void Store(ulong* address, Vector128<ulong> source) => Store(address, source); /// <summary> /// void _mm_storeu_pd (double* mem_addr, __m128d a) /// MOVUPD m128, xmm /// </summary> public static unsafe void Store(double* address, Vector128<double> source) => Store(address, source); /// <summary> /// void _mm_storeh_pd (double* mem_addr, __m128d a) /// MOVHPD m64, xmm /// </summary> public static unsafe void StoreHigh(double* address, Vector128<double> source) => StoreHigh(address, source); /// <summary> /// void _mm_storel_pd (double* mem_addr, __m128d a) /// MOVLPD m64, xmm /// </summary> public static unsafe void StoreLow(double* address, Vector128<double> source) => StoreLow(address, source); /// <summary> /// void _mm_stream_si32(int *p, int a) /// MOVNTI m32, r32 /// </summary> public static unsafe void StoreNonTemporal(int* address, int value) => StoreNonTemporal(address, value); /// <summary> /// void _mm_stream_si32(int *p, int a) /// MOVNTI m32, r32 /// </summary> public static unsafe void StoreNonTemporal(uint* address, uint value) => StoreNonTemporal(address, value); /// <summary> /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) /// PSUBB xmm, xmm/m128 /// </summary> public static Vector128<byte> Subtract(Vector128<byte> left, Vector128<byte> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi8 (__m128i a, __m128i b) /// PSUBB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Subtract(Vector128<sbyte> left, Vector128<sbyte> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) /// PSUBW xmm, xmm/m128 /// </summary> public static Vector128<short> Subtract(Vector128<short> left, Vector128<short> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi16 (__m128i a, __m128i b) /// PSUBW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Subtract(Vector128<ushort> left, Vector128<ushort> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) /// PSUBD xmm, xmm/m128 /// </summary> public static Vector128<int> Subtract(Vector128<int> left, Vector128<int> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi32 (__m128i a, __m128i b) /// PSUBD xmm, xmm/m128 /// </summary> public static Vector128<uint> Subtract(Vector128<uint> left, Vector128<uint> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) /// PSUBQ xmm, xmm/m128 /// </summary> public static Vector128<long> Subtract(Vector128<long> left, Vector128<long> right) => Subtract(left, right); /// <summary> /// __m128i _mm_sub_epi64 (__m128i a, __m128i b) /// PSUBQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> Subtract(Vector128<ulong> left, Vector128<ulong> right) => Subtract(left, right); /// <summary> /// __m128d _mm_sub_pd (__m128d a, __m128d b) /// SUBPD xmm, xmm/m128 /// </summary> public static Vector128<double> Subtract(Vector128<double> left, Vector128<double> right) => Subtract(left, right); /// <summary> /// __m128d _mm_sub_sd (__m128d a, __m128d b) /// SUBSD xmm, xmm/m64 /// </summary> public static Vector128<double> SubtractScalar(Vector128<double> left, Vector128<double> right) => SubtractScalar(left, right); /// <summary> /// __m128i _mm_subs_epi8 (__m128i a, __m128i b) /// PSUBSB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> SubtractSaturate(Vector128<sbyte> left, Vector128<sbyte> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_subs_epi16 (__m128i a, __m128i b) /// PSUBSW xmm, xmm/m128 /// </summary> public static Vector128<short> SubtractSaturate(Vector128<short> left, Vector128<short> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_subs_epu8 (__m128i a, __m128i b) /// PSUBUSB xmm, xmm/m128 /// </summary> public static Vector128<byte> SubtractSaturate(Vector128<byte> left, Vector128<byte> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_subs_epu16 (__m128i a, __m128i b) /// PSUBUSW xmm, xmm/m128 /// </summary> public static Vector128<ushort> SubtractSaturate(Vector128<ushort> left, Vector128<ushort> right) => SubtractSaturate(left, right); /// <summary> /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) /// PUNPCKHBW xmm, xmm/m128 /// </summary> public static Vector128<byte> UnpackHigh(Vector128<byte> left, Vector128<byte> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b) /// PUNPCKHBW xmm, xmm/m128 /// </summary> public static Vector128<sbyte> UnpackHigh(Vector128<sbyte> left, Vector128<sbyte> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) /// PUNPCKHWD xmm, xmm/m128 /// </summary> public static Vector128<short> UnpackHigh(Vector128<short> left, Vector128<short> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b) /// PUNPCKHWD xmm, xmm/m128 /// </summary> public static Vector128<ushort> UnpackHigh(Vector128<ushort> left, Vector128<ushort> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) /// PUNPCKHDQ xmm, xmm/m128 /// </summary> public static Vector128<int> UnpackHigh(Vector128<int> left, Vector128<int> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b) /// PUNPCKHDQ xmm, xmm/m128 /// </summary> public static Vector128<uint> UnpackHigh(Vector128<uint> left, Vector128<uint> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) /// PUNPCKHQDQ xmm, xmm/m128 /// </summary> public static Vector128<long> UnpackHigh(Vector128<long> left, Vector128<long> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b) /// PUNPCKHQDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> UnpackHigh(Vector128<ulong> left, Vector128<ulong> right) => UnpackHigh(left, right); /// <summary> /// __m128d _mm_unpackhi_pd (__m128d a, __m128d b) /// UNPCKHPD xmm, xmm/m128 /// </summary> public static Vector128<double> UnpackHigh(Vector128<double> left, Vector128<double> right) => UnpackHigh(left, right); /// <summary> /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) /// PUNPCKLBW xmm, xmm/m128 /// </summary> public static Vector128<byte> UnpackLow(Vector128<byte> left, Vector128<byte> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b) /// PUNPCKLBW xmm, xmm/m128 /// </summary> public static Vector128<sbyte> UnpackLow(Vector128<sbyte> left, Vector128<sbyte> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) /// PUNPCKLWD xmm, xmm/m128 /// </summary> public static Vector128<short> UnpackLow(Vector128<short> left, Vector128<short> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b) /// PUNPCKLWD xmm, xmm/m128 /// </summary> public static Vector128<ushort> UnpackLow(Vector128<ushort> left, Vector128<ushort> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) /// PUNPCKLDQ xmm, xmm/m128 /// </summary> public static Vector128<int> UnpackLow(Vector128<int> left, Vector128<int> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b) /// PUNPCKLDQ xmm, xmm/m128 /// </summary> public static Vector128<uint> UnpackLow(Vector128<uint> left, Vector128<uint> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) /// PUNPCKLQDQ xmm, xmm/m128 /// </summary> public static Vector128<long> UnpackLow(Vector128<long> left, Vector128<long> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b) /// PUNPCKLQDQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> UnpackLow(Vector128<ulong> left, Vector128<ulong> right) => UnpackLow(left, right); /// <summary> /// __m128d _mm_unpacklo_pd (__m128d a, __m128d b) /// UNPCKLPD xmm, xmm/m128 /// </summary> public static Vector128<double> UnpackLow(Vector128<double> left, Vector128<double> right) => UnpackLow(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<byte> Xor(Vector128<byte> left, Vector128<byte> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Xor(Vector128<sbyte> left, Vector128<sbyte> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<short> Xor(Vector128<short> left, Vector128<short> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<ushort> Xor(Vector128<ushort> left, Vector128<ushort> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<int> Xor(Vector128<int> left, Vector128<int> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<uint> Xor(Vector128<uint> left, Vector128<uint> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<long> Xor(Vector128<long> left, Vector128<long> right) => Xor(left, right); /// <summary> /// __m128i _mm_xor_si128 (__m128i a, __m128i b) /// PXOR xmm, xmm/m128 /// </summary> public static Vector128<ulong> Xor(Vector128<ulong> left, Vector128<ulong> right) => Xor(left, right); /// <summary> /// __m128d _mm_xor_pd (__m128d a, __m128d b) /// XORPD xmm, xmm/m128 /// </summary> public static Vector128<double> Xor(Vector128<double> left, Vector128<double> right) => Xor(left, right); } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/Common/tests/System/Xml/ModuleCore/XunitRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit.Abstractions; using Xunit.Sdk; namespace OLEDB.Test.ModuleCore { public class XmlInlineDataDiscoverer : IDataDiscoverer { public static IEnumerable<object[]> GenerateTestCases(Func<CTestModule> moduleGenerator) { CModInfo.CommandLine = ""; foreach (object[] testCase in GenerateTestCasesForModule(moduleGenerator())) { yield return testCase; } CModInfo.CommandLine = "/async"; foreach (object[] testCase in GenerateTestCasesForModule(moduleGenerator())) { yield return testCase; } } private static IEnumerable<object[]> GenerateTestCasesForModule(CTestModule module) { foreach (OLEDB.Test.ModuleCore.XunitTestCase testCase in module.TestCases()) { yield return new object[] { testCase }; } } private static Type ToRuntimeType(ITypeInfo typeInfo) { var reflectionTypeInfo = typeInfo as IReflectionTypeInfo; if (reflectionTypeInfo != null) return reflectionTypeInfo.Type; Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == typeInfo.Assembly.Name); if (assembly != null) { return assembly.GetType(typeInfo.Name); } throw new Exception($"Could not find runtime type `{typeInfo.Name}`"); } private static Type GetDeclaringType(IMethodInfo methodInfo) { var reflectionMethodInfo = methodInfo as IReflectionMethodInfo; if (reflectionMethodInfo != null) return reflectionMethodInfo.MethodInfo.DeclaringType; return ToRuntimeType(methodInfo.Type); } public virtual IEnumerable<object[]> GetData(IAttributeInfo dataAttribute, IMethodInfo testMethod) { string methodName = (string)dataAttribute.GetConstructorArguments().Single(); Func<CTestModule> moduleGenerator = XmlTestsAttribute.GetGenerator(GetDeclaringType(testMethod), methodName); return GenerateTestCases(moduleGenerator); } public virtual bool SupportsDiscoveryEnumeration(IAttributeInfo dataAttribute, IMethodInfo testMethod) => true; } [DataDiscoverer("OLEDB.Test.ModuleCore.XmlInlineDataDiscoverer", "ModuleCore")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class XmlTestsAttribute : DataAttribute { private delegate CTestModule ModuleGenerator(); private string _methodName; public XmlTestsAttribute(string methodName) { _methodName = methodName; } public static Func<CTestModule> GetGenerator(Type type, string methodName) { ModuleGenerator moduleGenerator = (ModuleGenerator)type.GetMethod(methodName).CreateDelegate(typeof(ModuleGenerator)); return new Func<CTestModule>(moduleGenerator); } public override IEnumerable<object[]> GetData(MethodInfo testMethod) { Func<CTestModule> moduleGenerator = GetGenerator(testMethod.DeclaringType, _methodName); return XmlInlineDataDiscoverer.GenerateTestCases(moduleGenerator); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit.Abstractions; using Xunit.Sdk; namespace OLEDB.Test.ModuleCore { public class XmlInlineDataDiscoverer : IDataDiscoverer { public static IEnumerable<object[]> GenerateTestCases(Func<CTestModule> moduleGenerator) { CModInfo.CommandLine = ""; foreach (object[] testCase in GenerateTestCasesForModule(moduleGenerator())) { yield return testCase; } CModInfo.CommandLine = "/async"; foreach (object[] testCase in GenerateTestCasesForModule(moduleGenerator())) { yield return testCase; } } private static IEnumerable<object[]> GenerateTestCasesForModule(CTestModule module) { foreach (OLEDB.Test.ModuleCore.XunitTestCase testCase in module.TestCases()) { yield return new object[] { testCase }; } } private static Type ToRuntimeType(ITypeInfo typeInfo) { var reflectionTypeInfo = typeInfo as IReflectionTypeInfo; if (reflectionTypeInfo != null) return reflectionTypeInfo.Type; Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == typeInfo.Assembly.Name); if (assembly != null) { return assembly.GetType(typeInfo.Name); } throw new Exception($"Could not find runtime type `{typeInfo.Name}`"); } private static Type GetDeclaringType(IMethodInfo methodInfo) { var reflectionMethodInfo = methodInfo as IReflectionMethodInfo; if (reflectionMethodInfo != null) return reflectionMethodInfo.MethodInfo.DeclaringType; return ToRuntimeType(methodInfo.Type); } public virtual IEnumerable<object[]> GetData(IAttributeInfo dataAttribute, IMethodInfo testMethod) { string methodName = (string)dataAttribute.GetConstructorArguments().Single(); Func<CTestModule> moduleGenerator = XmlTestsAttribute.GetGenerator(GetDeclaringType(testMethod), methodName); return GenerateTestCases(moduleGenerator); } public virtual bool SupportsDiscoveryEnumeration(IAttributeInfo dataAttribute, IMethodInfo testMethod) => true; } [DataDiscoverer("OLEDB.Test.ModuleCore.XmlInlineDataDiscoverer", "ModuleCore")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class XmlTestsAttribute : DataAttribute { private delegate CTestModule ModuleGenerator(); private string _methodName; public XmlTestsAttribute(string methodName) { _methodName = methodName; } public static Func<CTestModule> GetGenerator(Type type, string methodName) { ModuleGenerator moduleGenerator = (ModuleGenerator)type.GetMethod(methodName).CreateDelegate(typeof(ModuleGenerator)); return new Func<CTestModule>(moduleGenerator); } public override IEnumerable<object[]> GetData(MethodInfo testMethod) { Func<CTestModule> moduleGenerator = GetGenerator(testMethod.DeclaringType, _methodName); return XmlInlineDataDiscoverer.GenerateTestCases(moduleGenerator); } } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.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.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Speech.Internal.SapiInterop; namespace System.Speech.Internal.ObjectTokens { [DebuggerDisplay("{Name}")] internal class ObjectToken : RegistryDataKey, ISpObjectToken { #region Constructors protected ObjectToken(ISpObjectToken sapiObjectToken!!, bool disposeSapiToken) : base(sapiObjectToken) { _sapiObjectToken = sapiObjectToken; _disposeSapiObjectToken = disposeSapiToken; } /// <summary> /// Creates a ObjectToken from an already-existing ISpObjectToken. /// Assumes the token was created through enumeration, thus should not be disposed by us. /// </summary> /// <returns>ObjectToken object</returns> internal static ObjectToken Open(ISpObjectToken sapiObjectToken) { return new ObjectToken(sapiObjectToken, false); } /// <summary> /// Creates a new ObjectToken from a category /// Unlike the other Open overload, this one creates a new SAPI object, so Dispose must be called if /// you are creating ObjectTokens with this function. /// </summary> /// <returns>ObjectToken object</returns> internal static ObjectToken Open(string sCategoryId, string sTokenId, bool fCreateIfNotExist) { ISpObjectToken sapiObjectToken = (ISpObjectToken)new SpObjectToken(); try { sapiObjectToken.SetId(sCategoryId, sTokenId, fCreateIfNotExist); } catch (Exception) { Marshal.ReleaseComObject(sapiObjectToken); return null; } return new ObjectToken(sapiObjectToken, true); } protected override void Dispose(bool disposing) { try { if (disposing) { if (_disposeSapiObjectToken == true && _sapiObjectToken != null) { Marshal.ReleaseComObject(_sapiObjectToken); _sapiObjectToken = null; } if (_attributes != null) { _attributes.Dispose(); _attributes = null; } } } finally { base.Dispose(disposing); } } #endregion #region public Methods /// <summary> /// Tests whether two AutomationIdentifier objects are equivalent /// </summary> public override bool Equals(object obj) { ObjectToken token = obj as ObjectToken; return token != null && string.Equals(Id, token.Id, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Overrides Object.GetHashCode() /// </summary> public override int GetHashCode() { return Id.GetHashCode(); } #endregion #region Internal Properties internal RegistryDataKey Attributes { get { return _attributes != null ? _attributes : (_attributes = OpenKey("Attributes")); } } internal ISpObjectToken SAPIToken { get { return _sapiObjectToken; } } /// <summary> /// Returns the Age from a voice token /// </summary> internal string Age { get { string age; if (Attributes == null || !Attributes.TryGetString("Age", out age)) { age = string.Empty; } return age; } } /// <summary> /// Returns the gender /// </summary> internal string Gender { get { string gender; if (Attributes == null || !Attributes.TryGetString("Gender", out gender)) { gender = string.Empty; } return gender; } } /// <summary> /// Returns the Name for the voice /// Look first in the Name attribute, if not available then get the default string /// </summary> internal string TokenName() { string name = string.Empty; if (Attributes != null) { Attributes.TryGetString("Name", out name); if (string.IsNullOrEmpty(name)) { TryGetString(null, out name); } } return name; } /// <summary> /// Returns the Culture defined in the Language field for a token /// </summary> internal CultureInfo Culture { get { CultureInfo culture = null; string langId; if (Attributes.TryGetString("Language", out langId)) { culture = SapiAttributeParser.GetCultureInfoFromLanguageString(langId); } return culture; } } /// <summary> /// Returns the Culture defined in the Language field for a token /// </summary> internal string Description { get { string description = string.Empty; string sCultureId = string.Format(CultureInfo.InvariantCulture, "{0:x}", CultureInfo.CurrentUICulture.LCID); if (!TryGetString(sCultureId, out description)) { TryGetString(null, out description); } return description; } } #endregion #region internal Methods #region ISpObjectToken Implementation public void SetId([MarshalAs(UnmanagedType.LPWStr)] string pszCategoryId, [MarshalAs(UnmanagedType.LPWStr)] string pszTokenId, [MarshalAs(UnmanagedType.Bool)] bool fCreateIfNotExist) { throw new NotImplementedException(); } public void GetId([MarshalAs(UnmanagedType.LPWStr)] out IntPtr ppszCoMemTokenId) { ppszCoMemTokenId = Marshal.StringToCoTaskMemUni(Id); } public void Slot15() { throw new NotImplementedException(); } // void GetCategory(out ISpObjectTokenCategory ppTokenCategory); public void Slot16() { throw new NotImplementedException(); } // void CreateInstance(object pUnkOuter, UInt32 dwClsContext, ref Guid riid, ref IntPtr ppvObject); public void Slot17() { throw new NotImplementedException(); } // void GetStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] string pszFileNameSpecifier, UInt32 nFolder, [MarshalAs(UnmanagedType.LPWStr)] out string ppszFilePath); public void Slot18() { throw new NotImplementedException(); } // void RemoveStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszKeyName, int fDeleteFile); public void Slot19() { throw new NotImplementedException(); } // void Remove(ref Guid pclsidCaller); public void Slot20() { throw new NotImplementedException(); } // void IsUISupported([MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject, ref Int32 pfSupported); public void Slot21() { throw new NotImplementedException(); } // void DisplayUI(UInt32 hWndParent, [MarshalAs(UnmanagedType.LPWStr)] string pszTitle, [MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject); public void MatchesAttributes([MarshalAs(UnmanagedType.LPWStr)] string pszAttributes, [MarshalAs(UnmanagedType.Bool)] out bool pfMatches) { throw new NotImplementedException(); } #endregion /// <summary> /// Check if the token supports the attributes list given in. The /// attributes list has the same format as the required attributes given to /// SpEnumTokens. /// </summary> internal bool MatchesAttributes(string[] sAttributes) { bool fMatch = true; for (int iAttribute = 0; iAttribute < sAttributes.Length; iAttribute++) { string s = sAttributes[iAttribute]; fMatch &= HasValue(s) || (Attributes != null && Attributes.HasValue(s)); if (!fMatch) { break; } } return fMatch; } internal T CreateObjectFromToken<T>(string name) { T instanceValue = default(T); string clsid; if (!TryGetString(name, out clsid)) { throw new ArgumentException(SR.Get(SRID.TokenCannotCreateInstance)); } try { // Application Class Id Type type = Type.GetTypeFromCLSID(new Guid(clsid)); // Create the object instance instanceValue = (T)Activator.CreateInstance(type); // Initialize the instance ISpObjectWithToken objectWithToken = instanceValue as ISpObjectWithToken; if (objectWithToken != null) { int hresult = objectWithToken.SetObjectToken(this); if (hresult < 0) { throw new ArgumentException(SR.Get(SRID.TokenCannotCreateInstance)); } } else { Debug.Fail("Cannot query for interface " + typeof(ISpObjectWithToken).GUID + " from COM class " + clsid); } } catch (Exception e) { if (e is MissingMethodException || e is TypeLoadException || e is FileLoadException || e is FileNotFoundException || e is MethodAccessException || e is MemberAccessException || e is TargetInvocationException || e is InvalidComObjectException || e is NotSupportedException || e is FormatException) { throw new ArgumentException(SR.Get(SRID.TokenCannotCreateInstance)); } throw; } return instanceValue; } #endregion #region private Methods #endregion #region Private Types //--- ISpObjectWithToken ---------------------------------------------------- [ComImport, Guid("5B559F40-E952-11D2-BB91-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ISpObjectWithToken { [PreserveSig] int SetObjectToken(ISpObjectToken pToken); [PreserveSig] int GetObjectToken(IntPtr ppToken); } #endregion #region private Fields private ISpObjectToken _sapiObjectToken; private bool _disposeSapiObjectToken; private RegistryDataKey _attributes; #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.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Speech.Internal.SapiInterop; namespace System.Speech.Internal.ObjectTokens { [DebuggerDisplay("{Name}")] internal class ObjectToken : RegistryDataKey, ISpObjectToken { #region Constructors protected ObjectToken(ISpObjectToken sapiObjectToken!!, bool disposeSapiToken) : base(sapiObjectToken) { _sapiObjectToken = sapiObjectToken; _disposeSapiObjectToken = disposeSapiToken; } /// <summary> /// Creates a ObjectToken from an already-existing ISpObjectToken. /// Assumes the token was created through enumeration, thus should not be disposed by us. /// </summary> /// <returns>ObjectToken object</returns> internal static ObjectToken Open(ISpObjectToken sapiObjectToken) { return new ObjectToken(sapiObjectToken, false); } /// <summary> /// Creates a new ObjectToken from a category /// Unlike the other Open overload, this one creates a new SAPI object, so Dispose must be called if /// you are creating ObjectTokens with this function. /// </summary> /// <returns>ObjectToken object</returns> internal static ObjectToken Open(string sCategoryId, string sTokenId, bool fCreateIfNotExist) { ISpObjectToken sapiObjectToken = (ISpObjectToken)new SpObjectToken(); try { sapiObjectToken.SetId(sCategoryId, sTokenId, fCreateIfNotExist); } catch (Exception) { Marshal.ReleaseComObject(sapiObjectToken); return null; } return new ObjectToken(sapiObjectToken, true); } protected override void Dispose(bool disposing) { try { if (disposing) { if (_disposeSapiObjectToken == true && _sapiObjectToken != null) { Marshal.ReleaseComObject(_sapiObjectToken); _sapiObjectToken = null; } if (_attributes != null) { _attributes.Dispose(); _attributes = null; } } } finally { base.Dispose(disposing); } } #endregion #region public Methods /// <summary> /// Tests whether two AutomationIdentifier objects are equivalent /// </summary> public override bool Equals(object obj) { ObjectToken token = obj as ObjectToken; return token != null && string.Equals(Id, token.Id, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Overrides Object.GetHashCode() /// </summary> public override int GetHashCode() { return Id.GetHashCode(); } #endregion #region Internal Properties internal RegistryDataKey Attributes { get { return _attributes != null ? _attributes : (_attributes = OpenKey("Attributes")); } } internal ISpObjectToken SAPIToken { get { return _sapiObjectToken; } } /// <summary> /// Returns the Age from a voice token /// </summary> internal string Age { get { string age; if (Attributes == null || !Attributes.TryGetString("Age", out age)) { age = string.Empty; } return age; } } /// <summary> /// Returns the gender /// </summary> internal string Gender { get { string gender; if (Attributes == null || !Attributes.TryGetString("Gender", out gender)) { gender = string.Empty; } return gender; } } /// <summary> /// Returns the Name for the voice /// Look first in the Name attribute, if not available then get the default string /// </summary> internal string TokenName() { string name = string.Empty; if (Attributes != null) { Attributes.TryGetString("Name", out name); if (string.IsNullOrEmpty(name)) { TryGetString(null, out name); } } return name; } /// <summary> /// Returns the Culture defined in the Language field for a token /// </summary> internal CultureInfo Culture { get { CultureInfo culture = null; string langId; if (Attributes.TryGetString("Language", out langId)) { culture = SapiAttributeParser.GetCultureInfoFromLanguageString(langId); } return culture; } } /// <summary> /// Returns the Culture defined in the Language field for a token /// </summary> internal string Description { get { string description = string.Empty; string sCultureId = string.Format(CultureInfo.InvariantCulture, "{0:x}", CultureInfo.CurrentUICulture.LCID); if (!TryGetString(sCultureId, out description)) { TryGetString(null, out description); } return description; } } #endregion #region internal Methods #region ISpObjectToken Implementation public void SetId([MarshalAs(UnmanagedType.LPWStr)] string pszCategoryId, [MarshalAs(UnmanagedType.LPWStr)] string pszTokenId, [MarshalAs(UnmanagedType.Bool)] bool fCreateIfNotExist) { throw new NotImplementedException(); } public void GetId([MarshalAs(UnmanagedType.LPWStr)] out IntPtr ppszCoMemTokenId) { ppszCoMemTokenId = Marshal.StringToCoTaskMemUni(Id); } public void Slot15() { throw new NotImplementedException(); } // void GetCategory(out ISpObjectTokenCategory ppTokenCategory); public void Slot16() { throw new NotImplementedException(); } // void CreateInstance(object pUnkOuter, UInt32 dwClsContext, ref Guid riid, ref IntPtr ppvObject); public void Slot17() { throw new NotImplementedException(); } // void GetStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] string pszFileNameSpecifier, UInt32 nFolder, [MarshalAs(UnmanagedType.LPWStr)] out string ppszFilePath); public void Slot18() { throw new NotImplementedException(); } // void RemoveStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszKeyName, int fDeleteFile); public void Slot19() { throw new NotImplementedException(); } // void Remove(ref Guid pclsidCaller); public void Slot20() { throw new NotImplementedException(); } // void IsUISupported([MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject, ref Int32 pfSupported); public void Slot21() { throw new NotImplementedException(); } // void DisplayUI(UInt32 hWndParent, [MarshalAs(UnmanagedType.LPWStr)] string pszTitle, [MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject); public void MatchesAttributes([MarshalAs(UnmanagedType.LPWStr)] string pszAttributes, [MarshalAs(UnmanagedType.Bool)] out bool pfMatches) { throw new NotImplementedException(); } #endregion /// <summary> /// Check if the token supports the attributes list given in. The /// attributes list has the same format as the required attributes given to /// SpEnumTokens. /// </summary> internal bool MatchesAttributes(string[] sAttributes) { bool fMatch = true; for (int iAttribute = 0; iAttribute < sAttributes.Length; iAttribute++) { string s = sAttributes[iAttribute]; fMatch &= HasValue(s) || (Attributes != null && Attributes.HasValue(s)); if (!fMatch) { break; } } return fMatch; } internal T CreateObjectFromToken<T>(string name) { T instanceValue = default(T); string clsid; if (!TryGetString(name, out clsid)) { throw new ArgumentException(SR.Get(SRID.TokenCannotCreateInstance)); } try { // Application Class Id Type type = Type.GetTypeFromCLSID(new Guid(clsid)); // Create the object instance instanceValue = (T)Activator.CreateInstance(type); // Initialize the instance ISpObjectWithToken objectWithToken = instanceValue as ISpObjectWithToken; if (objectWithToken != null) { int hresult = objectWithToken.SetObjectToken(this); if (hresult < 0) { throw new ArgumentException(SR.Get(SRID.TokenCannotCreateInstance)); } } else { Debug.Fail("Cannot query for interface " + typeof(ISpObjectWithToken).GUID + " from COM class " + clsid); } } catch (Exception e) { if (e is MissingMethodException || e is TypeLoadException || e is FileLoadException || e is FileNotFoundException || e is MethodAccessException || e is MemberAccessException || e is TargetInvocationException || e is InvalidComObjectException || e is NotSupportedException || e is FormatException) { throw new ArgumentException(SR.Get(SRID.TokenCannotCreateInstance)); } throw; } return instanceValue; } #endregion #region private Methods #endregion #region Private Types //--- ISpObjectWithToken ---------------------------------------------------- [ComImport, Guid("5B559F40-E952-11D2-BB91-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ISpObjectWithToken { [PreserveSig] int SetObjectToken(ISpObjectToken pToken); [PreserveSig] int GetObjectToken(IntPtr ppToken); } #endregion #region private Fields private ISpObjectToken _sapiObjectToken; private bool _disposeSapiObjectToken; private RegistryDataKey _attributes; #endregion } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftLeftLogical.Vector128.UInt64.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 ShiftLeftLogical_Vector128_UInt64_1() { var test = new ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_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 ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray, UInt64[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt64, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1 testClass) { var result = AdvSimd.ShiftLeftLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1 testClass) { fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly byte Imm = 1; private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector128<UInt64> _clsVar; private Vector128<UInt64> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data, new UInt64[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.ShiftLeftLogical( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1(); var result = AdvSimd.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1(); fixed (Vector128<UInt64>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogical(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogical)}<UInt64>(Vector128<UInt64>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLeftLogical_Vector128_UInt64_1() { var test = new ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_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 ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray, UInt64[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt64, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1 testClass) { var result = AdvSimd.ShiftLeftLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1 testClass) { fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly byte Imm = 1; private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector128<UInt64> _clsVar; private Vector128<UInt64> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data, new UInt64[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.ShiftLeftLogical( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1(); var result = AdvSimd.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogical_Vector128_UInt64_1(); fixed (Vector128<UInt64>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogical( AdvSimd.LoadVector128((UInt64*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogical(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogical)}<UInt64>(Vector128<UInt64>, 1): {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,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.HandleMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Text.Json.Serialization; namespace System.Text.Json { public static partial class JsonSerializer { // Pre-encoded metadata properties. internal static readonly JsonEncodedText s_metadataId = JsonEncodedText.Encode("$id", encoder: null); internal static readonly JsonEncodedText s_metadataRef = JsonEncodedText.Encode("$ref", encoder: null); internal static readonly JsonEncodedText s_metadataValues = JsonEncodedText.Encode("$values", encoder: null); internal static MetadataPropertyName WriteReferenceForObject( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteString(s_metadataId, state.NewReferenceId); state.NewReferenceId = null; return MetadataPropertyName.Id; } return MetadataPropertyName.NoMetadata; } internal static MetadataPropertyName WriteReferenceForCollection( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteStartObject(); writer.WriteString(s_metadataId, state.NewReferenceId); writer.WriteStartArray(s_metadataValues); state.NewReferenceId = null; return MetadataPropertyName.Id; } // If the jsonConverter supports immutable enumerables or value type collections, don't write any metadata writer.WriteStartArray(); return MetadataPropertyName.NoMetadata; } /// <summary> /// Compute reference id for the next value to be serialized. /// </summary> internal static bool TryGetReferenceForValue(object currentValue, ref WriteStack state, Utf8JsonWriter writer) { Debug.Assert(state.NewReferenceId == null); string referenceId = state.ReferenceResolver.GetReference(currentValue, out bool alreadyExists); Debug.Assert(referenceId != null); if (alreadyExists) { // Instance already serialized, write as { "$ref" : "referenceId" } writer.WriteStartObject(); writer.WriteString(s_metadataRef, referenceId); writer.WriteEndObject(); } else { // New instance, store computed reference id in the state state.NewReferenceId = referenceId; } return alreadyExists; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Text.Json.Serialization; namespace System.Text.Json { public static partial class JsonSerializer { // Pre-encoded metadata properties. internal static readonly JsonEncodedText s_metadataId = JsonEncodedText.Encode("$id", encoder: null); internal static readonly JsonEncodedText s_metadataRef = JsonEncodedText.Encode("$ref", encoder: null); internal static readonly JsonEncodedText s_metadataValues = JsonEncodedText.Encode("$values", encoder: null); internal static MetadataPropertyName WriteReferenceForObject( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteString(s_metadataId, state.NewReferenceId); state.NewReferenceId = null; return MetadataPropertyName.Id; } return MetadataPropertyName.NoMetadata; } internal static MetadataPropertyName WriteReferenceForCollection( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteStartObject(); writer.WriteString(s_metadataId, state.NewReferenceId); writer.WriteStartArray(s_metadataValues); state.NewReferenceId = null; return MetadataPropertyName.Id; } // If the jsonConverter supports immutable enumerables or value type collections, don't write any metadata writer.WriteStartArray(); return MetadataPropertyName.NoMetadata; } /// <summary> /// Compute reference id for the next value to be serialized. /// </summary> internal static bool TryGetReferenceForValue(object currentValue, ref WriteStack state, Utf8JsonWriter writer) { Debug.Assert(state.NewReferenceId == null); string referenceId = state.ReferenceResolver.GetReference(currentValue, out bool alreadyExists); Debug.Assert(referenceId != null); if (alreadyExists) { // Instance already serialized, write as { "$ref" : "referenceId" } writer.WriteStartObject(); writer.WriteString(s_metadataRef, referenceId); writer.WriteEndObject(); } else { // New instance, store computed reference id in the state state.NewReferenceId = referenceId; } return alreadyExists; } } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/tests/Loader/classloader/generics/VSD/Class_ExplicitOverrideVirtualNewslotFinal.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Class_ExplicitOverrideVirtualNewslotFinal.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Class_ExplicitOverrideVirtualNewslotFinal.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/tests/baseservices/threading/generics/syncdelegate/thread14.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen<T> { void Target(); T Dummy(T t); } struct GenInt : IGen<int> { public int Dummy(int t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<int> obj = new GenInt(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenDouble : IGen<double> { public double Dummy(double t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<double> obj = new GenDouble(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenString : IGen<string> { public string Dummy(string t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<string> obj = new GenString(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenObject : IGen<object> { public object Dummy(object t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<object> obj = new GenObject(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenGuid : IGen<Guid> { public Guid Dummy(Guid t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<Guid> obj = new GenGuid(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } public class Test_thread14 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { GenInt.DelegateTest(); GenDouble.DelegateTest(); GenString.DelegateTest(); GenObject.DelegateTest(); GenGuid.DelegateTest(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen<T> { void Target(); T Dummy(T t); } struct GenInt : IGen<int> { public int Dummy(int t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<int> obj = new GenInt(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenDouble : IGen<double> { public double Dummy(double t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<double> obj = new GenDouble(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenString : IGen<string> { public string Dummy(string t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<string> obj = new GenString(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenObject : IGen<object> { public object Dummy(object t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<object> obj = new GenObject(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } struct GenGuid : IGen<Guid> { public Guid Dummy(Guid t) { return t; } public void Target() { Interlocked.Increment(ref Test_thread14.Xcounter); } public static void DelegateTest() { IGen<Guid> obj = new GenGuid(); ThreadStart d = new ThreadStart(obj.Target); d(); Test_thread14.Eval(Test_thread14.Xcounter==1); Test_thread14.Xcounter = 0; } } public class Test_thread14 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { GenInt.DelegateTest(); GenDouble.DelegateTest(); GenString.DelegateTest(); GenObject.DelegateTest(); GenGuid.DelegateTest(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.IO.UnmanagedMemoryStream/tests/HGlobalSafeBuffer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using Xunit; namespace System.IO.Tests { internal sealed class HGlobalSafeBuffer : SafeBuffer { internal HGlobalSafeBuffer(int capacity) : base(true) { SetHandle(Marshal.AllocHGlobal(capacity)); Initialize((ulong)capacity); } protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using Xunit; namespace System.IO.Tests { internal sealed class HGlobalSafeBuffer : SafeBuffer { internal HGlobalSafeBuffer(int capacity) : base(true) { SetHandle(Marshal.AllocHGlobal(capacity)); Initialize((ulong)capacity); } protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } }
-1
dotnet/runtime
66,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightArithmeticRounded.Vector128.SByte.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 ShiftRightArithmeticRounded_Vector128_SByte_1() { var test = new ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_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 ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray, SByte[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<SByte, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1 testClass) { var result = AdvSimd.ShiftRightArithmeticRounded(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1 testClass) { fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly byte Imm = 1; private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data, 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.ShiftRightArithmeticRounded( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticRounded), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticRounded), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightArithmeticRounded( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftRightArithmeticRounded(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftRightArithmeticRounded(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1(); var result = AdvSimd.ShiftRightArithmeticRounded(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1(); fixed (Vector128<SByte>* pFld = &test._fld) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightArithmeticRounded(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticRounded(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightArithmeticRounded(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightArithmeticRounded)}<SByte>(Vector128<SByte>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightArithmeticRounded_Vector128_SByte_1() { var test = new ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_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 ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray, SByte[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<SByte, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1 testClass) { var result = AdvSimd.ShiftRightArithmeticRounded(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1 testClass) { fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly byte Imm = 1; private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data, 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.ShiftRightArithmeticRounded( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticRounded), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticRounded), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightArithmeticRounded( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftRightArithmeticRounded(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftRightArithmeticRounded(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1(); var result = AdvSimd.ShiftRightArithmeticRounded(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRounded_Vector128_SByte_1(); fixed (Vector128<SByte>* pFld = &test._fld) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightArithmeticRounded(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticRounded(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightArithmeticRounded( AdvSimd.LoadVector128((SByte*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightArithmeticRounded(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightArithmeticRounded)}<SByte>(Vector128<SByte>, 1): {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,142
Use RegexGenerator in System.Private.Xml
Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
stephentoub
2022-03-03T14:28:29Z
2022-03-04T11:33:07Z
4a9d77052206d01ab5a62f16fb44f2f2a168babf
9053aa1e66ab7c1af7a14e649fb0bf0b0c501cde
Use RegexGenerator in System.Private.Xml. Closes https://github.com/dotnet/runtime/issues/62105 (I believe this is the only remaining place regexes are constructed from patterns known at compile time in libraries only targeting netcoreappcurrent).
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateExtensionsCommon.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.Security.Cryptography.X509Certificates { internal static class CertificateExtensionsCommon { public static T? GetPublicKey<T>( this X509Certificate2 certificate!!, Predicate<X509Certificate2>? matchesConstraints = null) where T : AsymmetricAlgorithm { string oidValue = GetExpectedOidValue<T>(); PublicKey publicKey = certificate.PublicKey; Oid algorithmOid = publicKey.Oid; if (oidValue != algorithmOid.Value) return null; if (matchesConstraints != null && !matchesConstraints(certificate)) return null; if (typeof(T) == typeof(RSA) || typeof(T) == typeof(DSA)) { byte[] rawEncodedKeyValue = publicKey.EncodedKeyValue.RawData; byte[] rawEncodedParameters = publicKey.EncodedParameters.RawData; return (T)(X509Pal.Instance.DecodePublicKey(algorithmOid, rawEncodedKeyValue, rawEncodedParameters, certificate.Pal)); } else if (typeof(T) == typeof(ECDsa)) { return (T)(object)(X509Pal.Instance.DecodeECDsaPublicKey(certificate.Pal)); } else if (typeof(T) == typeof(ECDiffieHellman)) { return (T)(object)(X509Pal.Instance.DecodeECDiffieHellmanPublicKey(certificate.Pal)); } Debug.Fail("Expected GetExpectedOidValue() to have thrown before we got here."); throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } public static T? GetPrivateKey<T>( this X509Certificate2 certificate!!, Predicate<X509Certificate2>? matchesConstraints = null) where T : AsymmetricAlgorithm { string oidValue = GetExpectedOidValue<T>(); if (!certificate.HasPrivateKey || oidValue != certificate.PublicKey.Oid.Value) return null; if (matchesConstraints != null && !matchesConstraints(certificate)) return null; if (typeof(T) == typeof(RSA)) return (T?)(object?)certificate.Pal.GetRSAPrivateKey(); if (typeof(T) == typeof(ECDsa)) return (T?)(object?)certificate.Pal.GetECDsaPrivateKey(); if (typeof(T) == typeof(DSA)) return (T?)(object?)certificate.Pal.GetDSAPrivateKey(); if (typeof(T) == typeof(ECDiffieHellman)) return (T?)(object?)certificate.Pal.GetECDiffieHellmanPrivateKey(); Debug.Fail("Expected GetExpectedOidValue() to have thrown before we got here."); throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } private static string GetExpectedOidValue<T>() where T : AsymmetricAlgorithm { if (typeof(T) == typeof(RSA)) return Oids.Rsa; if (typeof(T) == typeof(ECDsa) || typeof(T) == typeof(ECDiffieHellman)) // Neither Windows nor OpenSSL permit id-ECDH as the SPKI public key algorithm. return Oids.EcPublicKey; if (typeof(T) == typeof(DSA)) return Oids.Dsa; throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } } }
// 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.Security.Cryptography.X509Certificates { internal static class CertificateExtensionsCommon { public static T? GetPublicKey<T>( this X509Certificate2 certificate!!, Predicate<X509Certificate2>? matchesConstraints = null) where T : AsymmetricAlgorithm { string oidValue = GetExpectedOidValue<T>(); PublicKey publicKey = certificate.PublicKey; Oid algorithmOid = publicKey.Oid; if (oidValue != algorithmOid.Value) return null; if (matchesConstraints != null && !matchesConstraints(certificate)) return null; if (typeof(T) == typeof(RSA) || typeof(T) == typeof(DSA)) { byte[] rawEncodedKeyValue = publicKey.EncodedKeyValue.RawData; byte[] rawEncodedParameters = publicKey.EncodedParameters.RawData; return (T)(X509Pal.Instance.DecodePublicKey(algorithmOid, rawEncodedKeyValue, rawEncodedParameters, certificate.Pal)); } else if (typeof(T) == typeof(ECDsa)) { return (T)(object)(X509Pal.Instance.DecodeECDsaPublicKey(certificate.Pal)); } else if (typeof(T) == typeof(ECDiffieHellman)) { return (T)(object)(X509Pal.Instance.DecodeECDiffieHellmanPublicKey(certificate.Pal)); } Debug.Fail("Expected GetExpectedOidValue() to have thrown before we got here."); throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } public static T? GetPrivateKey<T>( this X509Certificate2 certificate!!, Predicate<X509Certificate2>? matchesConstraints = null) where T : AsymmetricAlgorithm { string oidValue = GetExpectedOidValue<T>(); if (!certificate.HasPrivateKey || oidValue != certificate.PublicKey.Oid.Value) return null; if (matchesConstraints != null && !matchesConstraints(certificate)) return null; if (typeof(T) == typeof(RSA)) return (T?)(object?)certificate.Pal.GetRSAPrivateKey(); if (typeof(T) == typeof(ECDsa)) return (T?)(object?)certificate.Pal.GetECDsaPrivateKey(); if (typeof(T) == typeof(DSA)) return (T?)(object?)certificate.Pal.GetDSAPrivateKey(); if (typeof(T) == typeof(ECDiffieHellman)) return (T?)(object?)certificate.Pal.GetECDiffieHellmanPrivateKey(); Debug.Fail("Expected GetExpectedOidValue() to have thrown before we got here."); throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } private static string GetExpectedOidValue<T>() where T : AsymmetricAlgorithm { if (typeof(T) == typeof(RSA)) return Oids.Rsa; if (typeof(T) == typeof(ECDsa) || typeof(T) == typeof(ECDiffieHellman)) // Neither Windows nor OpenSSL permit id-ECDH as the SPKI public key algorithm. return Oids.EcPublicKey; if (typeof(T) == typeof(DSA)) return Oids.Dsa; throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } } }
-1