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,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Security.Permissions/src/System/Security/Permissions/ReflectionPermissionAttribute.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.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage((AttributeTargets)(109), AllowMultiple = true, Inherited = false)]
public sealed partial class ReflectionPermissionAttribute : CodeAccessSecurityAttribute
{
public ReflectionPermissionAttribute(SecurityAction action) : base(default(SecurityAction)) { }
public ReflectionPermissionFlag Flags { get; set; }
public bool MemberAccess { get; set; }
[Obsolete("ReflectionPermissionAttribute.ReflectionEmit has been deprecated and is not supported.")]
public bool ReflectionEmit { get; set; }
public bool RestrictedMemberAccess { get; set; }
[Obsolete("ReflectionPermissionAttribute.TypeInformation has been deprecated and is not supported.")]
public bool TypeInformation { get; set; }
public override IPermission CreatePermission() { return default(IPermission); }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage((AttributeTargets)(109), AllowMultiple = true, Inherited = false)]
public sealed partial class ReflectionPermissionAttribute : CodeAccessSecurityAttribute
{
public ReflectionPermissionAttribute(SecurityAction action) : base(default(SecurityAction)) { }
public ReflectionPermissionFlag Flags { get; set; }
public bool MemberAccess { get; set; }
[Obsolete("ReflectionPermissionAttribute.ReflectionEmit has been deprecated and is not supported.")]
public bool ReflectionEmit { get; set; }
public bool RestrictedMemberAccess { get; set; }
[Obsolete("ReflectionPermissionAttribute.TypeInformation has been deprecated and is not supported.")]
public bool TypeInformation { get; set; }
public override IPermission CreatePermission() { return default(IPermission); }
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Globalization.Calendars/tests/TaiwanCalendar/TaiwanCalendarIsLeapMonth.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.Globalization.Tests
{
public class TaiwanCalendarIsLeapMonth
{
[Fact]
public void IsLeapMonth_ReturnsFalse()
{
TaiwanCalendar calendar = new TaiwanCalendar();
Assert.False(calendar.IsLeapMonth(TaiwanCalendarUtilities.RandomYear(), TaiwanCalendarUtilities.RandomMonth()));
Assert.False(calendar.IsLeapMonth(TaiwanCalendarUtilities.RandomYear(), TaiwanCalendarUtilities.RandomMonth(), 0));
Assert.False(calendar.IsLeapMonth(TaiwanCalendarUtilities.RandomYear(), TaiwanCalendarUtilities.RandomMonth(), 1));
}
}
}
| // 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.Globalization.Tests
{
public class TaiwanCalendarIsLeapMonth
{
[Fact]
public void IsLeapMonth_ReturnsFalse()
{
TaiwanCalendar calendar = new TaiwanCalendar();
Assert.False(calendar.IsLeapMonth(TaiwanCalendarUtilities.RandomYear(), TaiwanCalendarUtilities.RandomMonth()));
Assert.False(calendar.IsLeapMonth(TaiwanCalendarUtilities.RandomYear(), TaiwanCalendarUtilities.RandomMonth(), 0));
Assert.False(calendar.IsLeapMonth(TaiwanCalendarUtilities.RandomYear(), TaiwanCalendarUtilities.RandomMonth(), 1));
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/nativeaot/SmokeTests/DynamicGenerics/Assertion.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Note: Exception messages call ToString instead of Name to avoid MissingMetadataException when just outputting basic info
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CoreFXTestLibrary
{
/// <summary>
/// A collection of helper classes to test various conditions within
/// unit tests. If the condition being tested is not met, an exception
/// is thrown.
/// </summary>
public static class Assert
{
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentNullException"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="ArgumentNullException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <see cref="ArgumentNullException"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static ArgumentNullException ThrowsArgumentNullException(string parameterName, Action action, string message = null)
{
return ThrowsArgumentException<ArgumentNullException>(parameterName, action, message);
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentException"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="ArgumentException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <see cref="ArgumentException"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static ArgumentException ThrowsArgumentException(string parameterName, Action action, string message = null)
{
return ThrowsArgumentException<ArgumentException>(parameterName, action, message);
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentException"/> of type <typeparamref name="T"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static T ThrowsArgumentException<T>(string parameterName, Action action, string message = null)
where T : ArgumentException
{
T exception = Throws<T>(action, message);
#if DEBUG
// ParamName's not available on ret builds
if (parameterName != null)
Assert.AreEqual(parameterName, exception.ParamName, "Expected '{0}.ParamName' to be '{1}'. {2}", typeof(T), parameterName, message);
#endif
return exception;
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="AggregateException"/> with a base exception <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <returns>
/// The base <see cref="Exception"/> of the <see cref="AggregateException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="AggregateException"/> of was not thrown.
/// -or-
/// </para>
/// <see cref="AggregateException.GetBaseException()"/> is not of type <typeparam name="TBase"/>.
/// </exception>
public static TBase ThrowsAggregateException<TBase>(Action action, string message = "") where TBase : Exception
{
AggregateException exception = Throws<AggregateException>(action, message);
Exception baseException = exception.GetBaseException();
if (baseException == null)
Assert.Fail("Expected 'AggregateException.GetBaseException()' to be '{0}', however it is null. {1}", typeof(TBase), message);
if (baseException.GetType() != typeof(TBase))
Assert.Fail("Expected 'AggregateException.GetBaseException()', to be '{0}', however, '{1}' is. {2}", typeof(TBase), baseException.GetType(), message);
return (TBase)baseException;
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="format">
/// A <see cref="String"/> containing format information for when the assertion fails.
/// </param>
/// <param name="args">
/// An <see cref="Array"/> of arguments to be formatted.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static T Throws<T>(Action action, string format, params Object[] args) where T : Exception
{
return Throws<T>(action, String.Format(format, args));
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static T Throws<T>(Action action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None) where T : Exception
{
Exception exception = RunWithCatch(action);
if (exception == null)
Assert.Fail("Expected '{0}' to be thrown. {1}", typeof(T).ToString(), message);
if (!IsOfExceptionType<T>(exception, options))
Assert.Fail("Expected '{0}' to be thrown, however '{1}' was thrown. {2}", typeof(T), exception.GetType(), message);
return (T)exception;
}
/// <summary>
/// Asserts that the given async delegate throws an <see cref="Exception"/> of type <typeparam name="T".
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Func{}"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static async Task<T> ThrowsAsync<T>(Func<Task> action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None) where T : Exception
{
Exception exception = await RunWithCatchAsync(action);
if (exception == null)
Assert.Fail("Expected '{0}' to be thrown. {1}", typeof(T).ToString(), message);
if (!IsOfExceptionType<T>(exception, options))
Assert.Fail("Expected '{0}' to be thrown, however '{1}' was thrown. {2}", typeof(T), exception.GetType(), message);
return (T)exception;
}
/// <summary>
/// Asserts that the given async delegate throws an <see cref="Exception"/> of type <typeparam name="T" /> and <see cref="Exception.InnerException"/>
/// returns an <see cref="Exception"/> of type <typeparam name="TInner" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown inner <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="Exception.InnerException"/> is not of type <typeparam name="TInner"/>.
/// </exception>
public static TInner Throws<T, TInner>(Action action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None)
where T : Exception
where TInner : Exception
{
T outerException = Throws<T>(action, message, options);
if (outerException.InnerException == null)
Assert.Fail("Expected '{0}.InnerException' to be '{1}', however it is null. {2}", typeof(T), typeof(TInner), message);
if (!IsOfExceptionType<TInner>(outerException.InnerException, options))
Assert.Fail("Expected '{0}.InnerException', to be '{1}', however, '{2}' is. {3}", typeof(T), typeof(TInner), outerException.InnerException.GetType(), message);
return (TInner)outerException.InnerException;
}
/// <summary>
/// Tests whether the specified condition is true and throws an exception
/// if the condition is false.
/// </summary>
/// <param name="condition">The condition the test expects to be true.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is false. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is false.
/// </exception>
public static void IsTrue(bool condition, string format, params Object[] args)
{
if (!condition)
{
Assert.HandleFail("Assert.IsTrue", String.Format(format, args));
}
}
/// <summary>
/// Tests whether the specified condition is true and throws an exception
/// if the condition is false.
/// </summary>
/// <param name="condition">The condition the test expects to be true.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is false. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is false.
/// </exception>
public static void IsTrue(bool condition, string message = "")
{
if (!condition)
{
Assert.HandleFail("Assert.IsTrue", message);
}
}
/// <summary>
/// Tests whether the specified condition is false and throws an exception
/// if the condition is true.
/// </summary>
/// <param name="condition">The condition the test expects to be false.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is true. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is true.
/// </exception>
public static void IsFalse(bool condition, string message = "")
{
if (condition)
{
Assert.HandleFail("Assert.IsFalse", message);
}
}
/// <summary>
/// Tests whether the specified condition is false and throws an exception
/// if the condition is true.
/// </summary>
/// <param name="condition">The condition the test expects to be false.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is true. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is true.
/// </exception>
public static void IsFalse(bool condition, string format, params Object[] args)
{
IsFalse(condition, String.Format(format, args));
}
/// <summary>
/// Tests whether the specified object is null and throws an exception
/// if it is not.
/// </summary>
/// <param name="value">The object the test expects to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is not null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is not null.
/// </exception>
public static void IsNull(object value, string message = "")
{
if (value != null)
{
Assert.HandleFail("Assert.IsNull", message);
}
}
/// <summary>
/// Tests whether the specified object is null and throws an exception
/// if it is not.
/// </summary>
/// <param name="value">The object the test expects to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is not null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is not null.
/// </exception>
public static void IsNull(object value, string format, params Object[] args)
{
IsNull(value, String.Format(format, args));
}
/// <summary>
/// Tests whether the specified object is non-null and throws an exception
/// if it is null.
/// </summary>
/// <param name="value">The object the test expects not to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is null.
/// </exception>
public static void IsNotNull(object value, string message = "")
{
if (value == null)
{
Assert.HandleFail("Assert.IsNotNull", message);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreEqual<T>(T expected, T actual, string message = "")
{
const string EXPECTED_MSG = @"Expected: [{1}]. Actual: [{2}]. {0}";
if (!Object.Equals(expected, actual))
{
string finalMessage = String.Format(EXPECTED_MSG, message, (object)expected ?? "NULL", (object)actual ?? "NULL");
Assert.HandleFail("Assert.AreEqual", finalMessage);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreEqual<T>(T expected, T actual, string format, params Object[] args)
{
AreEqual<T>(expected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object that we do not want it to be.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreNotEqual<T>(T notExpected, T actual, string message = "")
{
if (Object.Equals(notExpected, actual))
{
String finalMessage =
String.Format(@"Expected any value except:[{1}]. Actual:[{2}]. {0}",
message, notExpected, actual);
Assert.HandleFail("Assert.AreNotEqual", finalMessage);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object that we do not want it to be.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreNotEqual<T>(T notExpected, T actual, string format, params Object[] args)
{
AreNotEqual<T>(notExpected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(T[] expected, T[] actual, string message = "")
{
Assert.AreEqual(expected.Length, actual.Length, message);
for (int i = 0; i < expected.Length; i++)
Assert.AreEqual<T>(expected[i], actual[i], message);
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(T[] expected, T[] actual, string format, params Object[] args)
{
AreAllEqual<T>(expected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) (but not necessarily in the same order) and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqualUnordered<T>(T[] expected, T[] actual)
{
Assert.AreEqual(expected.Length, actual.Length);
int count = expected.Length;
bool[] removedFromActual = new bool[count];
for (int i = 0; i < count; i++)
{
T item1 = expected[i];
bool foundMatch = false;
for (int j = 0; j < count; j++)
{
if (!removedFromActual[j])
{
T item2 = actual[j];
if ((item1 == null && item2 == null) || (item1 != null && item1.Equals(item2)))
{
foundMatch = true;
removedFromActual[j] = true;
break;
}
}
}
if (!foundMatch)
Assert.HandleFail("Assert.AreAllEqualUnordered", "First array has element not found in second array: " + item1);
}
return;
}
/// <summary>
/// Tests whether the two enumerables are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected enumerables.</param>
/// <param name="actual">Actual enumerables.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, string message = "")
{
AreAllEqual(CopyToArray(expected), CopyToArray(actual), message);
}
/// <summary>
/// Tests whether the two enumerables are the same length and contain the same objects (using Object.Equals()) (but not necessarily
/// in the same order) and throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected enumerable.</param>
/// <param name="actual">Actual enumerable.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqualUnordered<T>(IEnumerable<T> expected, IEnumerable<T> actual, string message = "")
{
AreAllEqualUnordered(CopyToArray(expected), CopyToArray(actual), message);
}
/// <summary>
/// Iterates through an IEnumerable to generate an array of elements. The rational for using this instead of
/// System.Linq.ToArray is that this will not require a dependency on System.Linq.dll
/// </summary>
private static T[] CopyToArray<T>(IEnumerable<T> source)
{
T[] items = new T[4];
int count = 0;
if (source == null)
return null;
foreach (var item in source)
{
if (items.Length == count)
{
var newItems = new T[checked(count * 2)];
Array.Copy(items, 0, newItems, 0, count);
items = newItems;
}
items[count] = item;
count++;
}
if (items.Length == count)
return items;
var finalItems = new T[count];
Array.Copy(items, 0, finalItems, 0, count);
return finalItems;
}
/// <summary>
/// Tests whether the specified objects both refer to the same object and
/// throws an exception if the two inputs do not refer to the same object.
/// </summary>
/// <param name="expected">
/// The first object to compare. This is the value the test expects.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="expected"/> does not refer to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreSame(object expected, object actual)
{
Assert.AreSame(expected, actual, string.Empty);
}
/// <summary>
/// Tests whether the specified objects both refer to the same object and
/// throws an exception if the two inputs do not refer to the same object.
/// </summary>
/// <param name="expected">
/// The first object to compare. This is the value the test expects.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <param name="message">
/// The message to include in the exception when <paramref name="actual"/>
/// is not the same as <paramref name="expected"/>. The message is shown
/// in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="expected"/> does not refer to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreSame(object expected, object actual, string message)
{
if (!Object.ReferenceEquals(expected, actual))
{
string finalMessage = message;
ValueType valExpected = expected as ValueType;
if (valExpected != null)
{
ValueType valActual = actual as ValueType;
if (valActual != null)
{
finalMessage = message == null ? String.Empty : message;
}
}
Assert.HandleFail("Assert.AreSame", finalMessage);
}
}
/// <summary>
/// Tests whether the specified objects refer to different objects and
/// throws an exception if the two inputs refer to the same object.
/// </summary>
/// <param name="notExpected">
/// The first object to compare. This is the value the test expects not
/// to match <paramref name="actual"/>.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="notExpected"/> refers to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreNotSame(object notExpected, object actual)
{
Assert.AreNotSame(notExpected, actual, string.Empty);
}
/// <summary>
/// Tests whether the specified objects refer to different objects and
/// throws an exception if the two inputs refer to the same object.
/// </summary>
/// <param name="notExpected">
/// The first object to compare. This is the value the test expects not
/// to match <paramref name="actual"/>.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <param name="message">
/// The message to include in the exception when <paramref name="actual"/>
/// is the same as <paramref name="notExpected"/>. The message is shown in
/// test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="notExpected"/> refers to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreNotSame(object notExpected, object actual, string message)
{
if (Object.ReferenceEquals(notExpected, actual))
{
Assert.HandleFail("Assert.AreNotSame", message);
}
}
/// <summary>
/// Throws an AssertFailedException.
/// </summary>
/// <exception cref="AssertFailedException">
/// Always thrown.
/// </exception>
public static void Fail()
{
Assert.HandleFail("Assert.Fail", "");
}
/// <summary>
/// Throws an AssertFailedException.
/// </summary>
/// <param name="message">
/// The message to include in the exception. The message is shown in
/// test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Always thrown.
/// </exception>
public static void Fail(string message, params object[] args)
{
string exceptionMessage = args.Length == 0 ? message : string.Format(message, args);
Assert.HandleFail("Assert.Fail", exceptionMessage);
}
/// <summary>
/// Helper function that creates and throws an exception.
/// </summary>
/// <param name="assertionName">name of the assertion throwing an exception.</param>
/// <param name="message">message describing conditions for assertion failure.</param>
/// <param name="parameters">The parameters.</param>
/// TODO: Modify HandleFail to take in parameters
internal static void HandleFail(string assertionName, string message)
{
// change this to use AssertFailedException
Logger.LogInformation(assertionName + ":" + message);
throw new AssertTestException(assertionName + ": " + message);
}
[Obsolete("Did you mean to call Assert.AreEqual()")]
public static new bool Equals(Object o1, Object o2)
{
Assert.Fail("Don\u2019t call this.");
throw new Exception();
}
private static bool IsOfExceptionType<T>(Exception thrown, AssertThrowsOptions options)
{
if ((options & AssertThrowsOptions.AllowDerived) == AssertThrowsOptions.AllowDerived)
return thrown is T;
return thrown.GetType() == typeof(T);
}
private static Exception RunWithCatch(Action action)
{
try
{
action();
return null;
}
catch (Exception ex)
{
return ex;
}
}
private static async Task<Exception> RunWithCatchAsync(Func<Task> action)
{
try
{
await action();
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
/// <summary>
/// Exception raised by the Assert on Fail
/// </summary>
public class AssertTestException : Exception
{
public AssertTestException(string message)
: base(message)
{
}
public AssertTestException()
: base()
{
}
}
public static class ExceptionAssert
{
public static void Throws<T>(String message, Action a) where T : Exception
{
Assert.Throws<T>(a, message);
}
}
/// <summary>
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception.
/// </summary>
[Flags]
public enum AssertThrowsOptions
{
/// <summary>
/// Specifies that <see cref="Assert.Throws{T}"/> should require an exact type
/// match when comparing the specified exception type with the throw exception.
/// </summary>
None = 0,
/// <summary>
/// Specifies that <see cref="Assert.Throws{T}"/> should not require an exact type
/// match when comparing the specified exception type with the thrown exception.
/// </summary>
AllowDerived = 1,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Note: Exception messages call ToString instead of Name to avoid MissingMetadataException when just outputting basic info
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CoreFXTestLibrary
{
/// <summary>
/// A collection of helper classes to test various conditions within
/// unit tests. If the condition being tested is not met, an exception
/// is thrown.
/// </summary>
public static class Assert
{
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentNullException"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="ArgumentNullException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <see cref="ArgumentNullException"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static ArgumentNullException ThrowsArgumentNullException(string parameterName, Action action, string message = null)
{
return ThrowsArgumentException<ArgumentNullException>(parameterName, action, message);
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentException"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="ArgumentException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <see cref="ArgumentException"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static ArgumentException ThrowsArgumentException(string parameterName, Action action, string message = null)
{
return ThrowsArgumentException<ArgumentException>(parameterName, action, message);
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentException"/> of type <typeparamref name="T"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static T ThrowsArgumentException<T>(string parameterName, Action action, string message = null)
where T : ArgumentException
{
T exception = Throws<T>(action, message);
#if DEBUG
// ParamName's not available on ret builds
if (parameterName != null)
Assert.AreEqual(parameterName, exception.ParamName, "Expected '{0}.ParamName' to be '{1}'. {2}", typeof(T), parameterName, message);
#endif
return exception;
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="AggregateException"/> with a base exception <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <returns>
/// The base <see cref="Exception"/> of the <see cref="AggregateException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="AggregateException"/> of was not thrown.
/// -or-
/// </para>
/// <see cref="AggregateException.GetBaseException()"/> is not of type <typeparam name="TBase"/>.
/// </exception>
public static TBase ThrowsAggregateException<TBase>(Action action, string message = "") where TBase : Exception
{
AggregateException exception = Throws<AggregateException>(action, message);
Exception baseException = exception.GetBaseException();
if (baseException == null)
Assert.Fail("Expected 'AggregateException.GetBaseException()' to be '{0}', however it is null. {1}", typeof(TBase), message);
if (baseException.GetType() != typeof(TBase))
Assert.Fail("Expected 'AggregateException.GetBaseException()', to be '{0}', however, '{1}' is. {2}", typeof(TBase), baseException.GetType(), message);
return (TBase)baseException;
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="format">
/// A <see cref="String"/> containing format information for when the assertion fails.
/// </param>
/// <param name="args">
/// An <see cref="Array"/> of arguments to be formatted.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static T Throws<T>(Action action, string format, params Object[] args) where T : Exception
{
return Throws<T>(action, String.Format(format, args));
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static T Throws<T>(Action action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None) where T : Exception
{
Exception exception = RunWithCatch(action);
if (exception == null)
Assert.Fail("Expected '{0}' to be thrown. {1}", typeof(T).ToString(), message);
if (!IsOfExceptionType<T>(exception, options))
Assert.Fail("Expected '{0}' to be thrown, however '{1}' was thrown. {2}", typeof(T), exception.GetType(), message);
return (T)exception;
}
/// <summary>
/// Asserts that the given async delegate throws an <see cref="Exception"/> of type <typeparam name="T".
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Func{}"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static async Task<T> ThrowsAsync<T>(Func<Task> action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None) where T : Exception
{
Exception exception = await RunWithCatchAsync(action);
if (exception == null)
Assert.Fail("Expected '{0}' to be thrown. {1}", typeof(T).ToString(), message);
if (!IsOfExceptionType<T>(exception, options))
Assert.Fail("Expected '{0}' to be thrown, however '{1}' was thrown. {2}", typeof(T), exception.GetType(), message);
return (T)exception;
}
/// <summary>
/// Asserts that the given async delegate throws an <see cref="Exception"/> of type <typeparam name="T" /> and <see cref="Exception.InnerException"/>
/// returns an <see cref="Exception"/> of type <typeparam name="TInner" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown inner <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="Exception.InnerException"/> is not of type <typeparam name="TInner"/>.
/// </exception>
public static TInner Throws<T, TInner>(Action action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None)
where T : Exception
where TInner : Exception
{
T outerException = Throws<T>(action, message, options);
if (outerException.InnerException == null)
Assert.Fail("Expected '{0}.InnerException' to be '{1}', however it is null. {2}", typeof(T), typeof(TInner), message);
if (!IsOfExceptionType<TInner>(outerException.InnerException, options))
Assert.Fail("Expected '{0}.InnerException', to be '{1}', however, '{2}' is. {3}", typeof(T), typeof(TInner), outerException.InnerException.GetType(), message);
return (TInner)outerException.InnerException;
}
/// <summary>
/// Tests whether the specified condition is true and throws an exception
/// if the condition is false.
/// </summary>
/// <param name="condition">The condition the test expects to be true.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is false. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is false.
/// </exception>
public static void IsTrue(bool condition, string format, params Object[] args)
{
if (!condition)
{
Assert.HandleFail("Assert.IsTrue", String.Format(format, args));
}
}
/// <summary>
/// Tests whether the specified condition is true and throws an exception
/// if the condition is false.
/// </summary>
/// <param name="condition">The condition the test expects to be true.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is false. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is false.
/// </exception>
public static void IsTrue(bool condition, string message = "")
{
if (!condition)
{
Assert.HandleFail("Assert.IsTrue", message);
}
}
/// <summary>
/// Tests whether the specified condition is false and throws an exception
/// if the condition is true.
/// </summary>
/// <param name="condition">The condition the test expects to be false.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is true. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is true.
/// </exception>
public static void IsFalse(bool condition, string message = "")
{
if (condition)
{
Assert.HandleFail("Assert.IsFalse", message);
}
}
/// <summary>
/// Tests whether the specified condition is false and throws an exception
/// if the condition is true.
/// </summary>
/// <param name="condition">The condition the test expects to be false.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is true. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is true.
/// </exception>
public static void IsFalse(bool condition, string format, params Object[] args)
{
IsFalse(condition, String.Format(format, args));
}
/// <summary>
/// Tests whether the specified object is null and throws an exception
/// if it is not.
/// </summary>
/// <param name="value">The object the test expects to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is not null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is not null.
/// </exception>
public static void IsNull(object value, string message = "")
{
if (value != null)
{
Assert.HandleFail("Assert.IsNull", message);
}
}
/// <summary>
/// Tests whether the specified object is null and throws an exception
/// if it is not.
/// </summary>
/// <param name="value">The object the test expects to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is not null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is not null.
/// </exception>
public static void IsNull(object value, string format, params Object[] args)
{
IsNull(value, String.Format(format, args));
}
/// <summary>
/// Tests whether the specified object is non-null and throws an exception
/// if it is null.
/// </summary>
/// <param name="value">The object the test expects not to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is null.
/// </exception>
public static void IsNotNull(object value, string message = "")
{
if (value == null)
{
Assert.HandleFail("Assert.IsNotNull", message);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreEqual<T>(T expected, T actual, string message = "")
{
const string EXPECTED_MSG = @"Expected: [{1}]. Actual: [{2}]. {0}";
if (!Object.Equals(expected, actual))
{
string finalMessage = String.Format(EXPECTED_MSG, message, (object)expected ?? "NULL", (object)actual ?? "NULL");
Assert.HandleFail("Assert.AreEqual", finalMessage);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreEqual<T>(T expected, T actual, string format, params Object[] args)
{
AreEqual<T>(expected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object that we do not want it to be.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreNotEqual<T>(T notExpected, T actual, string message = "")
{
if (Object.Equals(notExpected, actual))
{
String finalMessage =
String.Format(@"Expected any value except:[{1}]. Actual:[{2}]. {0}",
message, notExpected, actual);
Assert.HandleFail("Assert.AreNotEqual", finalMessage);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object that we do not want it to be.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreNotEqual<T>(T notExpected, T actual, string format, params Object[] args)
{
AreNotEqual<T>(notExpected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(T[] expected, T[] actual, string message = "")
{
Assert.AreEqual(expected.Length, actual.Length, message);
for (int i = 0; i < expected.Length; i++)
Assert.AreEqual<T>(expected[i], actual[i], message);
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(T[] expected, T[] actual, string format, params Object[] args)
{
AreAllEqual<T>(expected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) (but not necessarily in the same order) and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqualUnordered<T>(T[] expected, T[] actual)
{
Assert.AreEqual(expected.Length, actual.Length);
int count = expected.Length;
bool[] removedFromActual = new bool[count];
for (int i = 0; i < count; i++)
{
T item1 = expected[i];
bool foundMatch = false;
for (int j = 0; j < count; j++)
{
if (!removedFromActual[j])
{
T item2 = actual[j];
if ((item1 == null && item2 == null) || (item1 != null && item1.Equals(item2)))
{
foundMatch = true;
removedFromActual[j] = true;
break;
}
}
}
if (!foundMatch)
Assert.HandleFail("Assert.AreAllEqualUnordered", "First array has element not found in second array: " + item1);
}
return;
}
/// <summary>
/// Tests whether the two enumerables are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected enumerables.</param>
/// <param name="actual">Actual enumerables.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, string message = "")
{
AreAllEqual(CopyToArray(expected), CopyToArray(actual), message);
}
/// <summary>
/// Tests whether the two enumerables are the same length and contain the same objects (using Object.Equals()) (but not necessarily
/// in the same order) and throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected enumerable.</param>
/// <param name="actual">Actual enumerable.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqualUnordered<T>(IEnumerable<T> expected, IEnumerable<T> actual, string message = "")
{
AreAllEqualUnordered(CopyToArray(expected), CopyToArray(actual), message);
}
/// <summary>
/// Iterates through an IEnumerable to generate an array of elements. The rational for using this instead of
/// System.Linq.ToArray is that this will not require a dependency on System.Linq.dll
/// </summary>
private static T[] CopyToArray<T>(IEnumerable<T> source)
{
T[] items = new T[4];
int count = 0;
if (source == null)
return null;
foreach (var item in source)
{
if (items.Length == count)
{
var newItems = new T[checked(count * 2)];
Array.Copy(items, 0, newItems, 0, count);
items = newItems;
}
items[count] = item;
count++;
}
if (items.Length == count)
return items;
var finalItems = new T[count];
Array.Copy(items, 0, finalItems, 0, count);
return finalItems;
}
/// <summary>
/// Tests whether the specified objects both refer to the same object and
/// throws an exception if the two inputs do not refer to the same object.
/// </summary>
/// <param name="expected">
/// The first object to compare. This is the value the test expects.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="expected"/> does not refer to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreSame(object expected, object actual)
{
Assert.AreSame(expected, actual, string.Empty);
}
/// <summary>
/// Tests whether the specified objects both refer to the same object and
/// throws an exception if the two inputs do not refer to the same object.
/// </summary>
/// <param name="expected">
/// The first object to compare. This is the value the test expects.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <param name="message">
/// The message to include in the exception when <paramref name="actual"/>
/// is not the same as <paramref name="expected"/>. The message is shown
/// in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="expected"/> does not refer to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreSame(object expected, object actual, string message)
{
if (!Object.ReferenceEquals(expected, actual))
{
string finalMessage = message;
ValueType valExpected = expected as ValueType;
if (valExpected != null)
{
ValueType valActual = actual as ValueType;
if (valActual != null)
{
finalMessage = message == null ? String.Empty : message;
}
}
Assert.HandleFail("Assert.AreSame", finalMessage);
}
}
/// <summary>
/// Tests whether the specified objects refer to different objects and
/// throws an exception if the two inputs refer to the same object.
/// </summary>
/// <param name="notExpected">
/// The first object to compare. This is the value the test expects not
/// to match <paramref name="actual"/>.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="notExpected"/> refers to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreNotSame(object notExpected, object actual)
{
Assert.AreNotSame(notExpected, actual, string.Empty);
}
/// <summary>
/// Tests whether the specified objects refer to different objects and
/// throws an exception if the two inputs refer to the same object.
/// </summary>
/// <param name="notExpected">
/// The first object to compare. This is the value the test expects not
/// to match <paramref name="actual"/>.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <param name="message">
/// The message to include in the exception when <paramref name="actual"/>
/// is the same as <paramref name="notExpected"/>. The message is shown in
/// test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="notExpected"/> refers to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreNotSame(object notExpected, object actual, string message)
{
if (Object.ReferenceEquals(notExpected, actual))
{
Assert.HandleFail("Assert.AreNotSame", message);
}
}
/// <summary>
/// Throws an AssertFailedException.
/// </summary>
/// <exception cref="AssertFailedException">
/// Always thrown.
/// </exception>
public static void Fail()
{
Assert.HandleFail("Assert.Fail", "");
}
/// <summary>
/// Throws an AssertFailedException.
/// </summary>
/// <param name="message">
/// The message to include in the exception. The message is shown in
/// test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Always thrown.
/// </exception>
public static void Fail(string message, params object[] args)
{
string exceptionMessage = args.Length == 0 ? message : string.Format(message, args);
Assert.HandleFail("Assert.Fail", exceptionMessage);
}
/// <summary>
/// Helper function that creates and throws an exception.
/// </summary>
/// <param name="assertionName">name of the assertion throwing an exception.</param>
/// <param name="message">message describing conditions for assertion failure.</param>
/// <param name="parameters">The parameters.</param>
/// TODO: Modify HandleFail to take in parameters
internal static void HandleFail(string assertionName, string message)
{
// change this to use AssertFailedException
Logger.LogInformation(assertionName + ":" + message);
throw new AssertTestException(assertionName + ": " + message);
}
[Obsolete("Did you mean to call Assert.AreEqual()")]
public static new bool Equals(Object o1, Object o2)
{
Assert.Fail("Don\u2019t call this.");
throw new Exception();
}
private static bool IsOfExceptionType<T>(Exception thrown, AssertThrowsOptions options)
{
if ((options & AssertThrowsOptions.AllowDerived) == AssertThrowsOptions.AllowDerived)
return thrown is T;
return thrown.GetType() == typeof(T);
}
private static Exception RunWithCatch(Action action)
{
try
{
action();
return null;
}
catch (Exception ex)
{
return ex;
}
}
private static async Task<Exception> RunWithCatchAsync(Func<Task> action)
{
try
{
await action();
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
/// <summary>
/// Exception raised by the Assert on Fail
/// </summary>
public class AssertTestException : Exception
{
public AssertTestException(string message)
: base(message)
{
}
public AssertTestException()
: base()
{
}
}
public static class ExceptionAssert
{
public static void Throws<T>(String message, Action a) where T : Exception
{
Assert.Throws<T>(a, message);
}
}
/// <summary>
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception.
/// </summary>
[Flags]
public enum AssertThrowsOptions
{
/// <summary>
/// Specifies that <see cref="Assert.Throws{T}"/> should require an exact type
/// match when comparing the specified exception type with the throw exception.
/// </summary>
None = 0,
/// <summary>
/// Specifies that <see cref="Assert.Throws{T}"/> should not require an exact type
/// match when comparing the specified exception type with the thrown exception.
/// </summary>
AllowDerived = 1,
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b60723/b60723.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
namespace Test
{
using System;
public struct AA
{
public static bool m_bFwd2;
public static int Main()
{
try
{
Main1();
return 101;
}
catch (DivideByZeroException)
{
return 100;
}
}
public static void Main1()
{
try
{
bool local24 = true;
while (local24)
{
throw new DivideByZeroException();
}
}
finally
{
while (m_bFwd2) { }
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
namespace Test
{
using System;
public struct AA
{
public static bool m_bFwd2;
public static int Main()
{
try
{
Main1();
return 101;
}
catch (DivideByZeroException)
{
return 100;
}
}
public static void Main1()
{
try
{
bool local24 = true;
while (local24)
{
throw new DivideByZeroException();
}
}
finally
{
while (m_bFwd2) { }
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/Copy/Int64ArrayTests.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.Runtime.InteropServices.Tests
{
public class Int64ArrayTests
{
[Theory]
[InlineData(new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })]
public void CopyTo_Roundtrip_MatchesOriginalInput(long[] values)
{
int sizeOfArray = sizeof(long) * values.Length;
IntPtr ptr = Marshal.AllocCoTaskMem(sizeOfArray);
try
{
Marshal.Copy(values, 0, ptr, values.Length);
long[] array1 = new long[values.Length];
Marshal.Copy(ptr, array1, 0, values.Length);
Assert.Equal<long>(values, array1);
Marshal.Copy(values, 2, ptr, values.Length - 4);
long[] array2 = new long[values.Length];
Marshal.Copy(ptr, array2, 2, values.Length - 4);
Assert.Equal<long>(values.AsSpan(2, values.Length - 4).ToArray(), array2.AsSpan(2, values.Length - 4).ToArray());
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
[Fact]
public void CopyTo_NullDestination_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("destination", () => Marshal.Copy(new long[10], 0, IntPtr.Zero, 0));
AssertExtensions.Throws<ArgumentNullException>("destination", () => Marshal.Copy(new IntPtr(1), (long[])null, 0, 0));
}
[Fact]
public void CopyTo_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => Marshal.Copy((long[])null, 0, new IntPtr(1), 0));
AssertExtensions.Throws<ArgumentNullException>("source", () => Marshal.Copy(IntPtr.Zero, new long[10], 0, 0));
}
[Fact]
public void CopyTo_NegativeStartIndex_ThrowsArgumentOutOfRangeException()
{
long[] array = new long[10];
IntPtr ptr = Marshal.AllocCoTaskMem(sizeof(long) * array.Length);
try
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(array, -1, ptr, 10));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => Marshal.Copy(ptr, array, -1, 10));
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
[Fact]
public void CopyTo_NegativeLength_ThrowsArgumentOutOfRangeException()
{
long[] array = new long[10];
IntPtr ptr = Marshal.AllocCoTaskMem(sizeof(long) * array.Length);
try
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(array, 0, ptr, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Marshal.Copy(ptr, array, 0, -1));
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
[Theory]
[InlineData(0, 11)]
[InlineData(11, 1)]
[InlineData(2, 10)]
public void CopyTo_InvalidStartIndexLength_ThrowsArgumentOutOfRangeException(int startIndex, int length)
{
long[] array = new long[10];
IntPtr ptr = Marshal.AllocCoTaskMem(sizeof(long) * array.Length);
try
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(array, startIndex, ptr, length));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(ptr, array, startIndex, length));
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
}
}
| // 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.Runtime.InteropServices.Tests
{
public class Int64ArrayTests
{
[Theory]
[InlineData(new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })]
public void CopyTo_Roundtrip_MatchesOriginalInput(long[] values)
{
int sizeOfArray = sizeof(long) * values.Length;
IntPtr ptr = Marshal.AllocCoTaskMem(sizeOfArray);
try
{
Marshal.Copy(values, 0, ptr, values.Length);
long[] array1 = new long[values.Length];
Marshal.Copy(ptr, array1, 0, values.Length);
Assert.Equal<long>(values, array1);
Marshal.Copy(values, 2, ptr, values.Length - 4);
long[] array2 = new long[values.Length];
Marshal.Copy(ptr, array2, 2, values.Length - 4);
Assert.Equal<long>(values.AsSpan(2, values.Length - 4).ToArray(), array2.AsSpan(2, values.Length - 4).ToArray());
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
[Fact]
public void CopyTo_NullDestination_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("destination", () => Marshal.Copy(new long[10], 0, IntPtr.Zero, 0));
AssertExtensions.Throws<ArgumentNullException>("destination", () => Marshal.Copy(new IntPtr(1), (long[])null, 0, 0));
}
[Fact]
public void CopyTo_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => Marshal.Copy((long[])null, 0, new IntPtr(1), 0));
AssertExtensions.Throws<ArgumentNullException>("source", () => Marshal.Copy(IntPtr.Zero, new long[10], 0, 0));
}
[Fact]
public void CopyTo_NegativeStartIndex_ThrowsArgumentOutOfRangeException()
{
long[] array = new long[10];
IntPtr ptr = Marshal.AllocCoTaskMem(sizeof(long) * array.Length);
try
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(array, -1, ptr, 10));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => Marshal.Copy(ptr, array, -1, 10));
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
[Fact]
public void CopyTo_NegativeLength_ThrowsArgumentOutOfRangeException()
{
long[] array = new long[10];
IntPtr ptr = Marshal.AllocCoTaskMem(sizeof(long) * array.Length);
try
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(array, 0, ptr, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Marshal.Copy(ptr, array, 0, -1));
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
[Theory]
[InlineData(0, 11)]
[InlineData(11, 1)]
[InlineData(2, 10)]
public void CopyTo_InvalidStartIndexLength_ThrowsArgumentOutOfRangeException(int startIndex, int length)
{
long[] array = new long[10];
IntPtr ptr = Marshal.AllocCoTaskMem(sizeof(long) * array.Length);
try
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(array, startIndex, ptr, length));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Marshal.Copy(ptr, array, startIndex, length));
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/JsonSerializerWrapperForString.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
/// <summary>
/// Base class for wrapping string-based JsonSerializer methods which allows tests to run under different configurations.
/// </summary>
public abstract partial class JsonSerializerWrapperForString
{
private static readonly JsonSerializerOptions _optionsWithSmallBuffer = new JsonSerializerOptions { DefaultBufferSize = 1 };
public static JsonSerializerWrapperForString SpanSerializer => new SpanSerializerWrapper();
public static JsonSerializerWrapperForString StringSerializer => new StringSerializerWrapper();
public static JsonSerializerWrapperForString AsyncStreamSerializer => new AsyncStreamSerializerWrapper();
public static JsonSerializerWrapperForString AsyncStreamSerializerWithSmallBuffer => new AsyncStreamSerializerWrapperWithSmallBuffer();
public static JsonSerializerWrapperForString SyncStreamSerializer => new SyncStreamSerializerWrapper();
public static JsonSerializerWrapperForString ReaderWriterSerializer => new ReaderWriterSerializerWrapper();
public static JsonSerializerWrapperForString DocumentSerializer => new DocumentSerializerWrapper();
public static JsonSerializerWrapperForString ElementSerializer => new ElementSerializerWrapper();
public static JsonSerializerWrapperForString NodeSerializer => new NodeSerializerWrapper();
private class SpanSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => true; // a 'null' value is supported via implicit operator.
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes(value, inputType, options);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes<T>(value, options);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes(value, inputType, context);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes(value, jsonTypeInfo);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize<T>(json.AsSpan(), options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize(json.AsSpan(), type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
return Task.FromResult(JsonSerializer.Deserialize(json.AsSpan(), jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
return Task.FromResult(JsonSerializer.Deserialize(json.AsSpan(), type, context));
}
}
private class StringSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => true;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Serialize(value, inputType, options));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Serialize(value, options));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
return Task.FromResult(JsonSerializer.Serialize(value, inputType, context));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
return Task.FromResult(JsonSerializer.Serialize(value, jsonTypeInfo));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize<T>(json, options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize(json, type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
return Task.FromResult(JsonSerializer.Deserialize(json, jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
return Task.FromResult(JsonSerializer.Deserialize(json, type, context));
}
}
private class AsyncStreamSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override async Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync(stream, value, inputType, options);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync<T>(stream, value, options);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync(stream, value, inputType, context);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync(stream, value, jsonTypeInfo);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync<T>((Stream)null, options ?? _optionsWithSmallBuffer);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync<T>(stream, options ?? _optionsWithSmallBuffer);
}
protected internal override async Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync((Stream)null, type, options ?? _optionsWithSmallBuffer);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync(stream, type, options ?? _optionsWithSmallBuffer);
}
protected internal override async Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync((Stream)null, jsonTypeInfo);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync(stream, jsonTypeInfo);
}
protected internal override async Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync((Stream)null, type, context);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync(stream, type, context);
}
}
private class AsyncStreamSerializerWrapperWithSmallBuffer : AsyncStreamSerializerWrapper
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
if (options == null)
{
options = _optionsWithSmallBuffer;
}
return base.SerializeWrapper(value, inputType, options);
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
return base.SerializeWrapper<T>(value, options);
}
}
private class SyncStreamSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
JsonSerializer.Serialize(stream, value, inputType, options);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
JsonSerializer.Serialize<T>(stream, value, options);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
using MemoryStream stream = new();
JsonSerializer.Serialize(stream, value, inputType, context);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
using MemoryStream stream = new();
JsonSerializer.Serialize(stream, value, jsonTypeInfo);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>((Stream)null, options ?? _optionsWithSmallBuffer));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize<T>(stream, options ?? _optionsWithSmallBuffer));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize((Stream)null, type, options ?? _optionsWithSmallBuffer));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(stream, type, options ?? _optionsWithSmallBuffer));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>((Stream)null, jsonTypeInfo));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize<T>(stream, jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize((Stream)null, type, context));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(stream, type, context));
}
}
private class ReaderWriterSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize(writer, value, inputType, options);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize<T>(writer, value, options);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize(writer, value, inputType, context);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize(writer, value, jsonTypeInfo);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize<T>(ref reader, options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(ref reader, type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(ref reader, jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(ref reader, type, context));
}
}
private class DocumentSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, inputType, options);
return Task.FromResult(GetStringFromDocument(document));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, options);
return Task.FromResult(GetStringFromDocument(document));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, inputType, context);
return Task.FromResult(GetStringFromDocument(document));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, jsonTypeInfo);
return Task.FromResult(GetStringFromDocument(document));
}
private string GetStringFromDocument(JsonDocument document)
{
// Emulate a null return value.
if (document is null)
{
return "null";
}
using MemoryStream stream = new();
using (Utf8JsonWriter writer = new(stream))
{
document.WriteTo(writer);
}
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>(document: null));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize<T>(options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(document: null, type));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize(type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>(document: null, jsonTypeInfo));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize<T>(jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(document: null, type, context));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize(type, context));
}
}
private class ElementSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
JsonElement element = JsonSerializer.SerializeToElement(value, inputType, options);
return Task.FromResult(GetStringFromElement(element));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
JsonElement element = JsonSerializer.SerializeToElement(value, options);
return Task.FromResult(GetStringFromElement(element));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
JsonElement element = JsonSerializer.SerializeToElement(value, inputType, context);
return Task.FromResult(GetStringFromElement(element));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
JsonElement element = JsonSerializer.SerializeToElement(value, jsonTypeInfo);
return Task.FromResult(GetStringFromElement(element));
}
private string GetStringFromElement(JsonElement element)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
element.WriteTo(writer);
}
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize<T>(options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize(type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize<T>(jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize(type, context));
}
}
private class NodeSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => true;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
JsonNode node = JsonSerializer.SerializeToNode(value, inputType, options);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
JsonNode node = JsonSerializer.SerializeToNode(value, options);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
JsonNode node = JsonSerializer.SerializeToNode(value, inputType, context);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
JsonNode node = JsonSerializer.SerializeToNode(value, jsonTypeInfo);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null node for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>(node: null));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize<T>(options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null node for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(node: null, type));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize(type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null node for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(node: null, jsonTypeInfo));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize<T>(jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(node: null, type));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize(type, 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.IO;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
/// <summary>
/// Base class for wrapping string-based JsonSerializer methods which allows tests to run under different configurations.
/// </summary>
public abstract partial class JsonSerializerWrapperForString
{
private static readonly JsonSerializerOptions _optionsWithSmallBuffer = new JsonSerializerOptions { DefaultBufferSize = 1 };
public static JsonSerializerWrapperForString SpanSerializer => new SpanSerializerWrapper();
public static JsonSerializerWrapperForString StringSerializer => new StringSerializerWrapper();
public static JsonSerializerWrapperForString AsyncStreamSerializer => new AsyncStreamSerializerWrapper();
public static JsonSerializerWrapperForString AsyncStreamSerializerWithSmallBuffer => new AsyncStreamSerializerWrapperWithSmallBuffer();
public static JsonSerializerWrapperForString SyncStreamSerializer => new SyncStreamSerializerWrapper();
public static JsonSerializerWrapperForString ReaderWriterSerializer => new ReaderWriterSerializerWrapper();
public static JsonSerializerWrapperForString DocumentSerializer => new DocumentSerializerWrapper();
public static JsonSerializerWrapperForString ElementSerializer => new ElementSerializerWrapper();
public static JsonSerializerWrapperForString NodeSerializer => new NodeSerializerWrapper();
private class SpanSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => true; // a 'null' value is supported via implicit operator.
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes(value, inputType, options);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes<T>(value, options);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes(value, inputType, context);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
byte[] result = JsonSerializer.SerializeToUtf8Bytes(value, jsonTypeInfo);
return Task.FromResult(Encoding.UTF8.GetString(result));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize<T>(json.AsSpan(), options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize(json.AsSpan(), type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
return Task.FromResult(JsonSerializer.Deserialize(json.AsSpan(), jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
return Task.FromResult(JsonSerializer.Deserialize(json.AsSpan(), type, context));
}
}
private class StringSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => true;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Serialize(value, inputType, options));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Serialize(value, options));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
return Task.FromResult(JsonSerializer.Serialize(value, inputType, context));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
return Task.FromResult(JsonSerializer.Serialize(value, jsonTypeInfo));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize<T>(json, options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
return Task.FromResult(JsonSerializer.Deserialize(json, type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
return Task.FromResult(JsonSerializer.Deserialize(json, jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
return Task.FromResult(JsonSerializer.Deserialize(json, type, context));
}
}
private class AsyncStreamSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override async Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync(stream, value, inputType, options);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync<T>(stream, value, options);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync(stream, value, inputType, context);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
using MemoryStream stream = new();
await JsonSerializer.SerializeAsync(stream, value, jsonTypeInfo);
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override async Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync<T>((Stream)null, options ?? _optionsWithSmallBuffer);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync<T>(stream, options ?? _optionsWithSmallBuffer);
}
protected internal override async Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync((Stream)null, type, options ?? _optionsWithSmallBuffer);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync(stream, type, options ?? _optionsWithSmallBuffer);
}
protected internal override async Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync((Stream)null, jsonTypeInfo);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync(stream, jsonTypeInfo);
}
protected internal override async Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return await JsonSerializer.DeserializeAsync((Stream)null, type, context);
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return await JsonSerializer.DeserializeAsync(stream, type, context);
}
}
private class AsyncStreamSerializerWrapperWithSmallBuffer : AsyncStreamSerializerWrapper
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
if (options == null)
{
options = _optionsWithSmallBuffer;
}
return base.SerializeWrapper(value, inputType, options);
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
return base.SerializeWrapper<T>(value, options);
}
}
private class SyncStreamSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
JsonSerializer.Serialize(stream, value, inputType, options);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
using MemoryStream stream = new();
JsonSerializer.Serialize<T>(stream, value, options);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
using MemoryStream stream = new();
JsonSerializer.Serialize(stream, value, inputType, context);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
using MemoryStream stream = new();
JsonSerializer.Serialize(stream, value, jsonTypeInfo);
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>((Stream)null, options ?? _optionsWithSmallBuffer));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize<T>(stream, options ?? _optionsWithSmallBuffer));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize((Stream)null, type, options ?? _optionsWithSmallBuffer));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(stream, type, options ?? _optionsWithSmallBuffer));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>((Stream)null, jsonTypeInfo));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize<T>(stream, jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null Stream for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize((Stream)null, type, context));
}
using MemoryStream stream = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(stream, type, context));
}
}
private class ReaderWriterSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize(writer, value, inputType, options);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize<T>(writer, value, options);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize(writer, value, inputType, context);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
JsonSerializer.Serialize(writer, value, jsonTypeInfo);
}
return Task.FromResult(Encoding.UTF8.GetString(stream.ToArray()));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize<T>(ref reader, options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(ref reader, type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(ref reader, jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
Utf8JsonReader reader = new(Encoding.UTF8.GetBytes(json));
return Task.FromResult(JsonSerializer.Deserialize(ref reader, type, context));
}
}
private class DocumentSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, inputType, options);
return Task.FromResult(GetStringFromDocument(document));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, options);
return Task.FromResult(GetStringFromDocument(document));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, inputType, context);
return Task.FromResult(GetStringFromDocument(document));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
JsonDocument document = JsonSerializer.SerializeToDocument(value, jsonTypeInfo);
return Task.FromResult(GetStringFromDocument(document));
}
private string GetStringFromDocument(JsonDocument document)
{
// Emulate a null return value.
if (document is null)
{
return "null";
}
using MemoryStream stream = new();
using (Utf8JsonWriter writer = new(stream))
{
document.WriteTo(writer);
}
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>(document: null));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize<T>(options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(document: null, type));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize(type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>(document: null, jsonTypeInfo));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize<T>(jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(document: null, type, context));
}
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.Deserialize(type, context));
}
}
private class ElementSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => false;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
JsonElement element = JsonSerializer.SerializeToElement(value, inputType, options);
return Task.FromResult(GetStringFromElement(element));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
JsonElement element = JsonSerializer.SerializeToElement(value, options);
return Task.FromResult(GetStringFromElement(element));
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
JsonElement element = JsonSerializer.SerializeToElement(value, inputType, context);
return Task.FromResult(GetStringFromElement(element));
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
JsonElement element = JsonSerializer.SerializeToElement(value, jsonTypeInfo);
return Task.FromResult(GetStringFromElement(element));
}
private string GetStringFromElement(JsonElement element)
{
using MemoryStream stream = new MemoryStream();
using (Utf8JsonWriter writer = new(stream))
{
element.WriteTo(writer);
}
return Encoding.UTF8.GetString(stream.ToArray());
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize<T>(options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize(type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize<T>(jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
using JsonDocument document = JsonDocument.Parse(json);
return Task.FromResult(document.RootElement.Deserialize(type, context));
}
}
private class NodeSerializerWrapper : JsonSerializerWrapperForString
{
protected internal override bool SupportsNullValueOnDeserialize => true;
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerOptions options = null)
{
JsonNode node = JsonSerializer.SerializeToNode(value, inputType, options);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonSerializerOptions options = null)
{
JsonNode node = JsonSerializer.SerializeToNode(value, options);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<string> SerializeWrapper(object value, Type inputType, JsonSerializerContext context)
{
JsonNode node = JsonSerializer.SerializeToNode(value, inputType, context);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<string> SerializeWrapper<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
JsonNode node = JsonSerializer.SerializeToNode(value, jsonTypeInfo);
// Emulate a null return value.
if (node is null)
{
return Task.FromResult("null");
}
return Task.FromResult(node.ToJsonString());
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null node for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize<T>(node: null));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize<T>(options));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerOptions options = null)
{
if (json is null)
{
// Emulate a null node for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(node: null, type));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize(type, options));
}
protected internal override Task<T> DeserializeWrapper<T>(string json, JsonTypeInfo<T> jsonTypeInfo)
{
if (json is null)
{
// Emulate a null node for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(node: null, jsonTypeInfo));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize<T>(jsonTypeInfo));
}
protected internal override Task<object> DeserializeWrapper(string json, Type type, JsonSerializerContext context)
{
if (json is null)
{
// Emulate a null document for API validation tests.
return Task.FromResult(JsonSerializer.Deserialize(node: null, type));
}
JsonNode node = JsonNode.Parse(json);
return Task.FromResult(node.Deserialize(type, context));
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/X86/Sse2/ShiftRightLogical.Int32.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.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalInt321()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt321
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt321 testClass)
{
var result = Sse2.ShiftRightLogical(_fld, 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<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public ImmUnaryOpTest__ShiftRightLogicalInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<Int32>>(_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 = Sse2.ShiftRightLogical(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((Int32*)(_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(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftRightLogical(
_clsVar,
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<Int32>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalInt321();
var result = Sse2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftRightLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftRightLogical(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 RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(firstOp[0] >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(firstOp[i] >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int32>(Vector128<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalInt321()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt321
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt321 testClass)
{
var result = Sse2.ShiftRightLogical(_fld, 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<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public ImmUnaryOpTest__ShiftRightLogicalInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<Int32>>(_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 = Sse2.ShiftRightLogical(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((Int32*)(_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(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftRightLogical(
_clsVar,
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<Int32>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalInt321();
var result = Sse2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftRightLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftRightLogical(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 RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(firstOp[0] >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(firstOp[i] >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int32>(Vector128<Int32><9>): {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,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/X86/Fma_Vector256/MultiplyAddNegated.Double.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplyAddNegatedDouble()
{
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyAddNegatedDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public Vector256<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddNegatedDouble testClass)
{
var result = Fma.MultiplyAddNegated(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddNegatedDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
fixed (Vector256<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private static Vector256<Double> _clsVar3;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private Vector256<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyAddNegatedDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleTernaryOpTest__MultiplyAddNegatedDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplyAddNegated(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplyAddNegated(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplyAddNegated(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
fixed (Vector256<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2)),
Avx.LoadVector256((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
var result = Fma.MultiplyAddNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
fixed (Vector256<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplyAddNegated(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
fixed (Vector256<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplyAddNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2)),
Avx.LoadVector256((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, Vector256<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Round(-(firstOp[0] * secondOp[0]) + thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Round(-(firstOp[i] * secondOp[i]) + thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplyAddNegated)}<Double>(Vector256<Double>, Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplyAddNegatedDouble()
{
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyAddNegatedDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public Vector256<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddNegatedDouble testClass)
{
var result = Fma.MultiplyAddNegated(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddNegatedDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
fixed (Vector256<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private static Vector256<Double> _clsVar3;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private Vector256<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyAddNegatedDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleTernaryOpTest__MultiplyAddNegatedDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplyAddNegated(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplyAddNegated(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplyAddNegated(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
fixed (Vector256<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2)),
Avx.LoadVector256((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
var result = Fma.MultiplyAddNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
fixed (Vector256<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplyAddNegated(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
fixed (Vector256<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplyAddNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplyAddNegated(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2)),
Avx.LoadVector256((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, Vector256<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Round(-(firstOp[0] * secondOp[0]) + thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Round(-(firstOp[i] * secondOp[i]) + thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplyAddNegated)}<Double>(Vector256<Double>, Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/Microsoft.Extensions.FileSystemGlobbing/tests/PatternSegments/WildcardPathSegmentTests.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 Microsoft.Extensions.FileSystemGlobbing.Internal.PathSegments;
using Xunit;
namespace Microsoft.Extensions.FileSystemGlobbing.Tests.PatternSegments
{
public class WildcardPathSegmentTests
{
[Theory]
[InlineData(StringComparison.Ordinal)]
[InlineData(StringComparison.OrdinalIgnoreCase)]
public void DefaultConstructor(StringComparison comparisonType)
{
var paramBegin = "begin";
var paramContains = new List<string> { "1", "2", "three" };
var paramEnd = "end";
var segment = new WildcardPathSegment(paramBegin, paramContains, paramEnd, comparisonType);
Assert.Equal(paramBegin, segment.BeginsWith);
Assert.Equal<string>(paramContains, segment.Contains);
Assert.Equal(paramEnd, segment.EndsWith);
}
[Theory]
[MemberData(nameof(GetPositiveOrdinalIgnoreCaseDataSample))]
public void PositiveOrdinalIgnoreCaseMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.True(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
[Theory]
[MemberData(nameof(GetNegativeOrdinalIgnoreCaseDataSample))]
public void NegativeOrdinalIgnoreCaseMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.False(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
[Theory]
[MemberData(nameof(GetPositiveOrdinalDataSample))]
public void PositiveOrdinalMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.True(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
[Theory]
[MemberData(nameof(GetNegativeOrdinalDataSample))]
public void NegativeOrdinalMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.False(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
public static IEnumerable<object[]> GetPositiveOrdinalIgnoreCaseDataSample()
{
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abBb123c", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aaac", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "acccc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aacc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aacc", "aa", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "acc", "ac", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abcdefgh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abCDEfgh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab123cd321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abcd321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ababcd321ef123gh", "ab", "cd", "ef", "gh");
}
public static IEnumerable<object[]> GetNegativeOrdinalIgnoreCaseDataSample()
{
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aa", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "cc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "a", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "bc", "a", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ac", "a", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abc", "a", "b", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "ab", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "abb", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ac", "ac", "c");
}
public static IEnumerable<object[]> GetPositiveOrdinalDataSample()
{
yield return WrapResult(StringComparison.Ordinal, "abc", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "abBb123c", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "aaac", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "Aaac", "A", "c");
yield return WrapResult(StringComparison.Ordinal, "acccC", "a", "C");
yield return WrapResult(StringComparison.Ordinal, "aacc", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "aAcc", "aA", "c");
yield return WrapResult(StringComparison.Ordinal, "acc", "ac", "c");
yield return WrapResult(StringComparison.Ordinal, "abcDefgh", "ab", "cD", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "aB123cd321ef123gh", "aB", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "abcd321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "ab", "CD", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcd321eF123gh", "ab", "cd", "eF", "gh");
}
public static IEnumerable<object[]> GetNegativeOrdinalDataSample()
{
yield return WrapResult(StringComparison.Ordinal, "aa", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "abc", "A", "c");
yield return WrapResult(StringComparison.Ordinal, "cc", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "a", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "bc", "a", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "ac", "a", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "abc", "a", "b", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "ab", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "abb", "c");
yield return WrapResult(StringComparison.Ordinal, "ac", "ac", "c");
yield return WrapResult(StringComparison.Ordinal, "abBb123C", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "Aaac", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "aAac", "A", "c");
yield return WrapResult(StringComparison.Ordinal, "aCc", "a", "C");
yield return WrapResult(StringComparison.Ordinal, "aacc", "aA", "c");
yield return WrapResult(StringComparison.Ordinal, "acc", "aC", "c");
yield return WrapResult(StringComparison.Ordinal, "abcDefgh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "aB123cd321ef123gh", "aB", "cd", "EF", "gh");
yield return WrapResult(StringComparison.Ordinal, "abcd321ef123gh", "ab", "cd", "efF", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "AB", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "ab", "CD", "EF", "gh");
}
private static object[] WrapResult(StringComparison comparisonType, params string[] values)
{
if (values == null || values.Length < 3)
{
throw new InvalidOperationException("At least three values are required to create a data sample");
}
var beginWith = values[1];
var endWith = values[values.Length - 1];
var contains = values.Skip(2).Take(values.Length - 3);
return new object[] { values[0], new WildcardPathSegment(beginWith, contains.ToList(), endWith, comparisonType) };
}
private static string Serialize(WildcardPathSegment segment)
{
return string.Format("{0}:{1}:{2}",
segment.BeginsWith,
string.Join(",", segment.Contains.ToArray()),
segment.EndsWith);
}
}
}
| // 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 Microsoft.Extensions.FileSystemGlobbing.Internal.PathSegments;
using Xunit;
namespace Microsoft.Extensions.FileSystemGlobbing.Tests.PatternSegments
{
public class WildcardPathSegmentTests
{
[Theory]
[InlineData(StringComparison.Ordinal)]
[InlineData(StringComparison.OrdinalIgnoreCase)]
public void DefaultConstructor(StringComparison comparisonType)
{
var paramBegin = "begin";
var paramContains = new List<string> { "1", "2", "three" };
var paramEnd = "end";
var segment = new WildcardPathSegment(paramBegin, paramContains, paramEnd, comparisonType);
Assert.Equal(paramBegin, segment.BeginsWith);
Assert.Equal<string>(paramContains, segment.Contains);
Assert.Equal(paramEnd, segment.EndsWith);
}
[Theory]
[MemberData(nameof(GetPositiveOrdinalIgnoreCaseDataSample))]
public void PositiveOrdinalIgnoreCaseMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.True(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
[Theory]
[MemberData(nameof(GetNegativeOrdinalIgnoreCaseDataSample))]
public void NegativeOrdinalIgnoreCaseMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.False(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
[Theory]
[MemberData(nameof(GetPositiveOrdinalDataSample))]
public void PositiveOrdinalMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.True(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
[Theory]
[MemberData(nameof(GetNegativeOrdinalDataSample))]
public void NegativeOrdinalMatch(string testSample, object segment)
{
var wildcardPathSegment = (WildcardPathSegment)segment;
Assert.False(
wildcardPathSegment.Match(testSample),
string.Format("[TestSample: {0}] [Wildcard: {1}]", testSample, Serialize(wildcardPathSegment)));
}
public static IEnumerable<object[]> GetPositiveOrdinalIgnoreCaseDataSample()
{
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abBb123c", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aaac", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "acccc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aacc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aacc", "aa", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "acc", "ac", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abcdefgh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abCDEfgh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab123cd321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abcd321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ababcd321ef123gh", "ab", "cd", "ef", "gh");
}
public static IEnumerable<object[]> GetNegativeOrdinalIgnoreCaseDataSample()
{
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "aa", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "cc", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "a", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "a", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "bc", "a", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ac", "a", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "abc", "a", "b", "b", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "ab", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ab", "abb", "c");
yield return WrapResult(StringComparison.OrdinalIgnoreCase, "ac", "ac", "c");
}
public static IEnumerable<object[]> GetPositiveOrdinalDataSample()
{
yield return WrapResult(StringComparison.Ordinal, "abc", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "abBb123c", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "aaac", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "Aaac", "A", "c");
yield return WrapResult(StringComparison.Ordinal, "acccC", "a", "C");
yield return WrapResult(StringComparison.Ordinal, "aacc", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "aAcc", "aA", "c");
yield return WrapResult(StringComparison.Ordinal, "acc", "ac", "c");
yield return WrapResult(StringComparison.Ordinal, "abcDefgh", "ab", "cD", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "aB123cd321ef123gh", "aB", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "abcd321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "ab", "CD", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcd321eF123gh", "ab", "cd", "eF", "gh");
}
public static IEnumerable<object[]> GetNegativeOrdinalDataSample()
{
yield return WrapResult(StringComparison.Ordinal, "aa", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "abc", "A", "c");
yield return WrapResult(StringComparison.Ordinal, "cc", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "a", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "bc", "a", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "ac", "a", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "abc", "a", "b", "b", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "ab", "c");
yield return WrapResult(StringComparison.Ordinal, "ab", "abb", "c");
yield return WrapResult(StringComparison.Ordinal, "ac", "ac", "c");
yield return WrapResult(StringComparison.Ordinal, "abBb123C", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "Aaac", "a", "c");
yield return WrapResult(StringComparison.Ordinal, "aAac", "A", "c");
yield return WrapResult(StringComparison.Ordinal, "aCc", "a", "C");
yield return WrapResult(StringComparison.Ordinal, "aacc", "aA", "c");
yield return WrapResult(StringComparison.Ordinal, "acc", "aC", "c");
yield return WrapResult(StringComparison.Ordinal, "abcDefgh", "ab", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "aB123cd321ef123gh", "aB", "cd", "EF", "gh");
yield return WrapResult(StringComparison.Ordinal, "abcd321ef123gh", "ab", "cd", "efF", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "AB", "cd", "ef", "gh");
yield return WrapResult(StringComparison.Ordinal, "ababcdCD321ef123gh", "ab", "CD", "EF", "gh");
}
private static object[] WrapResult(StringComparison comparisonType, params string[] values)
{
if (values == null || values.Length < 3)
{
throw new InvalidOperationException("At least three values are required to create a data sample");
}
var beginWith = values[1];
var endWith = values[values.Length - 1];
var contains = values.Skip(2).Take(values.Length - 3);
return new object[] { values[0], new WildcardPathSegment(beginWith, contains.ToList(), endWith, comparisonType) };
}
private static string Serialize(WildcardPathSegment segment)
{
return string.Format("{0}:{1}:{2}",
segment.BeginsWith,
string.Join(",", segment.Contains.ToArray()),
segment.EndsWith);
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Threading.Channels/tests/ChannelTests.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;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Channels.Tests
{
public class ChannelTests
{
[Fact]
public void ChannelOptimizations_Properties_Roundtrip()
{
var co = new UnboundedChannelOptions();
Assert.False(co.SingleReader);
Assert.False(co.SingleWriter);
co.SingleReader = true;
Assert.True(co.SingleReader);
Assert.False(co.SingleWriter);
co.SingleReader = false;
Assert.False(co.SingleReader);
co.SingleWriter = true;
Assert.False(co.SingleReader);
Assert.True(co.SingleWriter);
co.SingleWriter = false;
Assert.False(co.SingleWriter);
co.SingleReader = true;
co.SingleWriter = true;
Assert.True(co.SingleReader);
Assert.True(co.SingleWriter);
Assert.False(co.AllowSynchronousContinuations);
co.AllowSynchronousContinuations = true;
Assert.True(co.AllowSynchronousContinuations);
co.AllowSynchronousContinuations = false;
Assert.False(co.AllowSynchronousContinuations);
}
[Fact]
public void Create_ValidInputs_ProducesValidChannels()
{
Assert.NotNull(Channel.CreateBounded<int>(1));
Assert.NotNull(Channel.CreateBounded<int>(new BoundedChannelOptions(1)));
Assert.NotNull(Channel.CreateUnbounded<int>());
Assert.NotNull(Channel.CreateUnbounded<int>(new UnboundedChannelOptions()));
}
[Fact]
public void Create_NullOptions_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentNullException>("options", () => Channel.CreateUnbounded<int>(null));
AssertExtensions.Throws<ArgumentNullException>("options", () => Channel.CreateBounded<int>(null));
}
[Theory]
[InlineData(0)]
[InlineData(-2)]
public void CreateBounded_InvalidBufferSizes_ThrowArgumentExceptions(int capacity)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => Channel.CreateBounded<int>(capacity));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new BoundedChannelOptions(capacity));
}
[Theory]
[InlineData((BoundedChannelFullMode)(-1))]
[InlineData((BoundedChannelFullMode)(4))]
public void BoundedChannelOptions_InvalidModes_ThrowArgumentExceptions(BoundedChannelFullMode mode) =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new BoundedChannelOptions(1) { FullMode = mode });
[Theory]
[InlineData(0)]
[InlineData(-2)]
public void BoundedChannelOptions_InvalidCapacity_ThrowArgumentExceptions(int capacity) =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new BoundedChannelOptions(1) { Capacity = capacity });
[Theory]
[InlineData(1)]
public void CreateBounded_ValidBufferSizes_Success(int bufferedCapacity) =>
Assert.NotNull(Channel.CreateBounded<int>(bufferedCapacity));
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task DefaultWriteAsync_UsesWaitToWriteAsyncAndTryWrite()
{
var c = new TestChannelWriter<int>(10);
Assert.False(c.TryComplete());
Assert.Equal(TaskStatus.Canceled, c.WriteAsync(42, new CancellationToken(true)).AsTask().Status);
int count = 0;
try
{
while (true)
{
await c.WriteAsync(count++);
}
}
catch (ChannelClosedException) { }
Assert.Equal(11, count);
}
[Fact]
public void DefaultCompletion_NeverCompletes()
{
Task t = new TestChannelReader<int>(Enumerable.Empty<int>()).Completion;
Assert.False(t.IsCompleted);
}
[Fact]
public async Task DefaultWriteAsync_CatchesTryWriteExceptions()
{
var w = new TryWriteThrowingWriter<int>();
ValueTask t = w.WriteAsync(42);
Assert.True(t.IsFaulted);
await Assert.ThrowsAsync<FormatException>(async () => await t);
}
[Fact]
public async Task DefaultReadAsync_CatchesTryWriteExceptions()
{
var r = new TryReadThrowingReader<int>();
Task<int> t = r.ReadAsync().AsTask();
Assert.Equal(TaskStatus.Faulted, t.Status);
await Assert.ThrowsAsync<FieldAccessException>(() => t);
}
[Fact]
public async Task TestBaseClassReadAsync()
{
WrapperChannel<int> channel = new WrapperChannel<int>(10);
ChannelReader<int> reader = channel.Reader;
ChannelWriter<int> writer = channel.Writer;
// 1- do it through synchronous TryRead()
writer.TryWrite(50);
Assert.Equal(50, await reader.ReadAsync());
// 2- do it through async
ValueTask<int> readTask = reader.ReadAsync();
writer.TryWrite(100);
Assert.Equal(100, await readTask);
// 3- use cancellation token
CancellationToken ct = new CancellationToken(true); // cancelled token
await Assert.ThrowsAsync<TaskCanceledException>(() => reader.ReadAsync(ct).AsTask());
// 4- throw during reading
readTask = reader.ReadAsync();
((WrapperChannelReader<int>)reader).ForceThrowing = true;
writer.TryWrite(200);
await Assert.ThrowsAsync<InvalidOperationException>(() => readTask.AsTask());
// 5- close the channel while waiting reading
((WrapperChannelReader<int>)reader).ForceThrowing = false;
Assert.Equal(200, await reader.ReadAsync());
readTask = reader.ReadAsync();
channel.Writer.TryComplete();
await Assert.ThrowsAsync<ChannelClosedException>(() => readTask.AsTask());
}
[Fact]
public void TestBaseClassTryPeek()
{
var reader = new TryPeekNoOverrideReader<int>();
Assert.False(reader.CanPeek);
Assert.False(reader.TryPeek(out int item));
Assert.Equal(0, item);
}
// This reader doesn't override ReadAsync to force using the base class ReadAsync method
private sealed class WrapperChannelReader<T> : ChannelReader<T>
{
private ChannelReader<T> _reader;
internal bool ForceThrowing { get; set; }
public WrapperChannelReader(Channel<T> channel) {_reader = channel.Reader; }
public override bool TryRead(out T item)
{
if (ForceThrowing)
throw new InvalidOperationException();
return _reader.TryRead(out item);
}
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken)
{
return _reader.WaitToReadAsync(cancellationToken);
}
}
public class WrapperChannel<T> : Channel<T>
{
public WrapperChannel(int capacity)
{
Channel<T> channel = Channel.CreateBounded<T>(capacity);
Writer = channel.Writer;
Reader = new WrapperChannelReader<T>(channel);
}
}
private sealed class TestChannelWriter<T> : ChannelWriter<T>
{
private readonly Random _rand = new Random(42);
private readonly int _max;
private int _count;
public TestChannelWriter(int max) => _max = max;
public override bool TryWrite(T item) => _rand.Next(0, 2) == 0 && _count++ < _max; // succeed if we're under our limit, and add random failures
public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) =>
_count >= _max ? new ValueTask<bool>(Task.FromResult(false)) :
_rand.Next(0, 2) == 0 ? new ValueTask<bool>(Task.Delay(1).ContinueWith(_ => true)) : // randomly introduce delays
new ValueTask<bool>(Task.FromResult(true));
}
private sealed class TestChannelReader<T> : ChannelReader<T>
{
private Random _rand = new Random(42);
private IEnumerator<T> _enumerator;
private bool _closed;
public TestChannelReader(IEnumerable<T> enumerable) => _enumerator = enumerable.GetEnumerator();
public override bool TryRead(out T item)
{
// Randomly fail to read
if (_rand.Next(0, 2) == 0)
{
item = default;
return false;
}
// If the enumerable is closed, fail the read.
if (!_enumerator.MoveNext())
{
_enumerator.Dispose();
_closed = true;
item = default;
return false;
}
// Otherwise return the next item.
item = _enumerator.Current;
return true;
}
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) => new ValueTask<bool>(
_closed ? Task.FromResult(false) :
_rand.Next(0, 2) == 0 ? Task.Delay(1).ContinueWith(_ => true) : // randomly introduce delays
Task.FromResult(true));
}
private sealed class TryWriteThrowingWriter<T> : ChannelWriter<T>
{
public override bool TryWrite(T item) => throw new FormatException();
public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default) => throw new InvalidDataException();
}
private sealed class TryReadThrowingReader<T> : ChannelReader<T>
{
public override bool TryRead(out T item) => throw new FieldAccessException();
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default) => throw new DriveNotFoundException();
}
private sealed class TryPeekNoOverrideReader<T> : ChannelReader<T>
{
public override bool TryRead([MaybeNullWhen(false)] out T item)
{
item = default;
return false;
}
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) => default;
}
private sealed class CanReadFalseStream : MemoryStream
{
public override bool CanRead => false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Channels.Tests
{
public class ChannelTests
{
[Fact]
public void ChannelOptimizations_Properties_Roundtrip()
{
var co = new UnboundedChannelOptions();
Assert.False(co.SingleReader);
Assert.False(co.SingleWriter);
co.SingleReader = true;
Assert.True(co.SingleReader);
Assert.False(co.SingleWriter);
co.SingleReader = false;
Assert.False(co.SingleReader);
co.SingleWriter = true;
Assert.False(co.SingleReader);
Assert.True(co.SingleWriter);
co.SingleWriter = false;
Assert.False(co.SingleWriter);
co.SingleReader = true;
co.SingleWriter = true;
Assert.True(co.SingleReader);
Assert.True(co.SingleWriter);
Assert.False(co.AllowSynchronousContinuations);
co.AllowSynchronousContinuations = true;
Assert.True(co.AllowSynchronousContinuations);
co.AllowSynchronousContinuations = false;
Assert.False(co.AllowSynchronousContinuations);
}
[Fact]
public void Create_ValidInputs_ProducesValidChannels()
{
Assert.NotNull(Channel.CreateBounded<int>(1));
Assert.NotNull(Channel.CreateBounded<int>(new BoundedChannelOptions(1)));
Assert.NotNull(Channel.CreateUnbounded<int>());
Assert.NotNull(Channel.CreateUnbounded<int>(new UnboundedChannelOptions()));
}
[Fact]
public void Create_NullOptions_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentNullException>("options", () => Channel.CreateUnbounded<int>(null));
AssertExtensions.Throws<ArgumentNullException>("options", () => Channel.CreateBounded<int>(null));
}
[Theory]
[InlineData(0)]
[InlineData(-2)]
public void CreateBounded_InvalidBufferSizes_ThrowArgumentExceptions(int capacity)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => Channel.CreateBounded<int>(capacity));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new BoundedChannelOptions(capacity));
}
[Theory]
[InlineData((BoundedChannelFullMode)(-1))]
[InlineData((BoundedChannelFullMode)(4))]
public void BoundedChannelOptions_InvalidModes_ThrowArgumentExceptions(BoundedChannelFullMode mode) =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new BoundedChannelOptions(1) { FullMode = mode });
[Theory]
[InlineData(0)]
[InlineData(-2)]
public void BoundedChannelOptions_InvalidCapacity_ThrowArgumentExceptions(int capacity) =>
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new BoundedChannelOptions(1) { Capacity = capacity });
[Theory]
[InlineData(1)]
public void CreateBounded_ValidBufferSizes_Success(int bufferedCapacity) =>
Assert.NotNull(Channel.CreateBounded<int>(bufferedCapacity));
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task DefaultWriteAsync_UsesWaitToWriteAsyncAndTryWrite()
{
var c = new TestChannelWriter<int>(10);
Assert.False(c.TryComplete());
Assert.Equal(TaskStatus.Canceled, c.WriteAsync(42, new CancellationToken(true)).AsTask().Status);
int count = 0;
try
{
while (true)
{
await c.WriteAsync(count++);
}
}
catch (ChannelClosedException) { }
Assert.Equal(11, count);
}
[Fact]
public void DefaultCompletion_NeverCompletes()
{
Task t = new TestChannelReader<int>(Enumerable.Empty<int>()).Completion;
Assert.False(t.IsCompleted);
}
[Fact]
public async Task DefaultWriteAsync_CatchesTryWriteExceptions()
{
var w = new TryWriteThrowingWriter<int>();
ValueTask t = w.WriteAsync(42);
Assert.True(t.IsFaulted);
await Assert.ThrowsAsync<FormatException>(async () => await t);
}
[Fact]
public async Task DefaultReadAsync_CatchesTryWriteExceptions()
{
var r = new TryReadThrowingReader<int>();
Task<int> t = r.ReadAsync().AsTask();
Assert.Equal(TaskStatus.Faulted, t.Status);
await Assert.ThrowsAsync<FieldAccessException>(() => t);
}
[Fact]
public async Task TestBaseClassReadAsync()
{
WrapperChannel<int> channel = new WrapperChannel<int>(10);
ChannelReader<int> reader = channel.Reader;
ChannelWriter<int> writer = channel.Writer;
// 1- do it through synchronous TryRead()
writer.TryWrite(50);
Assert.Equal(50, await reader.ReadAsync());
// 2- do it through async
ValueTask<int> readTask = reader.ReadAsync();
writer.TryWrite(100);
Assert.Equal(100, await readTask);
// 3- use cancellation token
CancellationToken ct = new CancellationToken(true); // cancelled token
await Assert.ThrowsAsync<TaskCanceledException>(() => reader.ReadAsync(ct).AsTask());
// 4- throw during reading
readTask = reader.ReadAsync();
((WrapperChannelReader<int>)reader).ForceThrowing = true;
writer.TryWrite(200);
await Assert.ThrowsAsync<InvalidOperationException>(() => readTask.AsTask());
// 5- close the channel while waiting reading
((WrapperChannelReader<int>)reader).ForceThrowing = false;
Assert.Equal(200, await reader.ReadAsync());
readTask = reader.ReadAsync();
channel.Writer.TryComplete();
await Assert.ThrowsAsync<ChannelClosedException>(() => readTask.AsTask());
}
[Fact]
public void TestBaseClassTryPeek()
{
var reader = new TryPeekNoOverrideReader<int>();
Assert.False(reader.CanPeek);
Assert.False(reader.TryPeek(out int item));
Assert.Equal(0, item);
}
// This reader doesn't override ReadAsync to force using the base class ReadAsync method
private sealed class WrapperChannelReader<T> : ChannelReader<T>
{
private ChannelReader<T> _reader;
internal bool ForceThrowing { get; set; }
public WrapperChannelReader(Channel<T> channel) {_reader = channel.Reader; }
public override bool TryRead(out T item)
{
if (ForceThrowing)
throw new InvalidOperationException();
return _reader.TryRead(out item);
}
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken)
{
return _reader.WaitToReadAsync(cancellationToken);
}
}
public class WrapperChannel<T> : Channel<T>
{
public WrapperChannel(int capacity)
{
Channel<T> channel = Channel.CreateBounded<T>(capacity);
Writer = channel.Writer;
Reader = new WrapperChannelReader<T>(channel);
}
}
private sealed class TestChannelWriter<T> : ChannelWriter<T>
{
private readonly Random _rand = new Random(42);
private readonly int _max;
private int _count;
public TestChannelWriter(int max) => _max = max;
public override bool TryWrite(T item) => _rand.Next(0, 2) == 0 && _count++ < _max; // succeed if we're under our limit, and add random failures
public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) =>
_count >= _max ? new ValueTask<bool>(Task.FromResult(false)) :
_rand.Next(0, 2) == 0 ? new ValueTask<bool>(Task.Delay(1).ContinueWith(_ => true)) : // randomly introduce delays
new ValueTask<bool>(Task.FromResult(true));
}
private sealed class TestChannelReader<T> : ChannelReader<T>
{
private Random _rand = new Random(42);
private IEnumerator<T> _enumerator;
private bool _closed;
public TestChannelReader(IEnumerable<T> enumerable) => _enumerator = enumerable.GetEnumerator();
public override bool TryRead(out T item)
{
// Randomly fail to read
if (_rand.Next(0, 2) == 0)
{
item = default;
return false;
}
// If the enumerable is closed, fail the read.
if (!_enumerator.MoveNext())
{
_enumerator.Dispose();
_closed = true;
item = default;
return false;
}
// Otherwise return the next item.
item = _enumerator.Current;
return true;
}
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) => new ValueTask<bool>(
_closed ? Task.FromResult(false) :
_rand.Next(0, 2) == 0 ? Task.Delay(1).ContinueWith(_ => true) : // randomly introduce delays
Task.FromResult(true));
}
private sealed class TryWriteThrowingWriter<T> : ChannelWriter<T>
{
public override bool TryWrite(T item) => throw new FormatException();
public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default) => throw new InvalidDataException();
}
private sealed class TryReadThrowingReader<T> : ChannelReader<T>
{
public override bool TryRead(out T item) => throw new FieldAccessException();
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default) => throw new DriveNotFoundException();
}
private sealed class TryPeekNoOverrideReader<T> : ChannelReader<T>
{
public override bool TryRead([MaybeNullWhen(false)] out T item)
{
item = default;
return false;
}
public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) => default;
}
private sealed class CanReadFalseStream : MemoryStream
{
public override bool CanRead => false;
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/X86/Ssse3/Sign.Int32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SignInt32()
{
var test = new SimpleBinaryOpTest__SignInt32();
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__SignInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SignInt32 testClass)
{
var result = Ssse3.Sign(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SignInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SignInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__SignInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Ssse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Ssse3.Sign(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Ssse3.Sign(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Ssse3.Sign(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Ssse3.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Ssse3.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Ssse3.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SignInt32();
var result = Ssse3.Sign(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__SignInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Ssse3.Sign(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Ssse3.Sign(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 = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (right[0] < 0 ? (int)(-left[0]) : (right[0] > 0 ? left[0] : 0)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (right[i] < 0 ? (int)(-left[i]) : (right[i] > 0 ? left[i] : 0)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.Sign)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SignInt32()
{
var test = new SimpleBinaryOpTest__SignInt32();
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__SignInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SignInt32 testClass)
{
var result = Ssse3.Sign(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SignInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SignInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__SignInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Ssse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Ssse3.Sign(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Ssse3.Sign(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Sign), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Ssse3.Sign(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Ssse3.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Ssse3.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Ssse3.Sign(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SignInt32();
var result = Ssse3.Sign(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__SignInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Ssse3.Sign(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Ssse3.Sign(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 = Ssse3.Sign(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (right[0] < 0 ? (int)(-left[0]) : (right[0] > 0 ? left[0] : 0)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (right[i] < 0 ? (int)(-left[i]) : (right[i] > 0 ? left[i] : 0)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.Sign)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/NoMethodsCompilationModuleGroup.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 Internal.ReadyToRunConstants;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler
{
/// <summary>
/// A compilation group that only contains no methods. Used for creating an R2R image without
/// any method compiled into it. Needed for handling inputbubble scenarios where a dependent
/// assembly should not be R2R'd.
/// </summary>
public class NoMethodsCompilationModuleGroup : ReadyToRunCompilationModuleGroupBase
{
public NoMethodsCompilationModuleGroup(
CompilerTypeSystemContext context,
bool isCompositeBuildMode,
bool isInputBubble,
IEnumerable<EcmaModule> compilationModuleSet,
IEnumerable<ModuleDesc> versionBubbleModuleSet,
bool compileGenericDependenciesFromVersionBubbleModuleSet) :
base(context,
isCompositeBuildMode,
isInputBubble,
compilationModuleSet,
versionBubbleModuleSet,
compileGenericDependenciesFromVersionBubbleModuleSet)
{
}
public override bool ContainsMethodBody(MethodDesc method, bool unboxingStub)
{
return false;
}
public override void ApplyProfilerGuidedCompilationRestriction(ProfileDataManager profileGuidedCompileRestriction)
{
return;
}
public override ReadyToRunFlags GetReadyToRunFlags()
{
// Partial by definition.
return ReadyToRunFlags.READYTORUN_FLAG_Partial;
}
}
}
| // 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 Internal.ReadyToRunConstants;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler
{
/// <summary>
/// A compilation group that only contains no methods. Used for creating an R2R image without
/// any method compiled into it. Needed for handling inputbubble scenarios where a dependent
/// assembly should not be R2R'd.
/// </summary>
public class NoMethodsCompilationModuleGroup : ReadyToRunCompilationModuleGroupBase
{
public NoMethodsCompilationModuleGroup(
CompilerTypeSystemContext context,
bool isCompositeBuildMode,
bool isInputBubble,
IEnumerable<EcmaModule> compilationModuleSet,
IEnumerable<ModuleDesc> versionBubbleModuleSet,
bool compileGenericDependenciesFromVersionBubbleModuleSet) :
base(context,
isCompositeBuildMode,
isInputBubble,
compilationModuleSet,
versionBubbleModuleSet,
compileGenericDependenciesFromVersionBubbleModuleSet)
{
}
public override bool ContainsMethodBody(MethodDesc method, bool unboxingStub)
{
return false;
}
public override void ApplyProfilerGuidedCompilationRestriction(ProfileDataManager profileGuidedCompileRestriction)
{
return;
}
public override ReadyToRunFlags GetReadyToRunFlags()
{
// Partial by definition.
return ReadyToRunFlags.READYTORUN_FLAG_Partial;
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/FunctionalTests/WebAssembly/Browser/HotReload/Program.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Sample
{
public class Test
{
public static void Main(string[] args)
{
Console.WriteLine ("Hello, World!");
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static int TestMeaning()
{
const int success = 42;
const int failure = 1;
var ty = typeof(System.Reflection.Metadata.MetadataUpdater);
var mi = ty.GetMethod("GetCapabilities", BindingFlags.NonPublic | BindingFlags.Static, Array.Empty<Type>());
if (mi == null)
return failure;
var caps = mi.Invoke(null, null) as string;
if (String.IsNullOrEmpty(caps))
return failure;
var assm = typeof (ApplyUpdateReferencedAssembly.MethodBody1).Assembly;
var r = ApplyUpdateReferencedAssembly.MethodBody1.StaticMethod1();
if ("OLD STRING" != r)
return failure;
ApplyUpdate(assm);
r = ApplyUpdateReferencedAssembly.MethodBody1.StaticMethod1();
if ("NEW STRING" != r)
return failure;
ApplyUpdate(assm);
r = ApplyUpdateReferencedAssembly.MethodBody1.StaticMethod1();
if ("NEWEST STRING" != r)
return failure;
return success;
}
private static System.Collections.Generic.Dictionary<Assembly, int> assembly_count = new();
internal static void ApplyUpdate (System.Reflection.Assembly assm)
{
int count;
if (!assembly_count.TryGetValue(assm, out count))
count = 1;
else
count++;
assembly_count [assm] = count;
/* FIXME WASM: Location is empty on wasm. Make up a name based on Name */
string basename = assm.Location;
if (basename == "")
basename = assm.GetName().Name + ".dll";
Console.Error.WriteLine($"Apply Delta Update for {basename}, revision {count}");
string dmeta_name = $"{basename}.{count}.dmeta";
string dil_name = $"{basename}.{count}.dil";
byte[] dmeta_data = System.IO.File.ReadAllBytes(dmeta_name);
byte[] dil_data = System.IO.File.ReadAllBytes(dil_name);
byte[] dpdb_data = null; // TODO also use the dpdb data
System.Reflection.Metadata.MetadataUpdater.ApplyUpdate(assm, dmeta_data, dil_data, dpdb_data);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Sample
{
public class Test
{
public static void Main(string[] args)
{
Console.WriteLine ("Hello, World!");
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static int TestMeaning()
{
const int success = 42;
const int failure = 1;
var ty = typeof(System.Reflection.Metadata.MetadataUpdater);
var mi = ty.GetMethod("GetCapabilities", BindingFlags.NonPublic | BindingFlags.Static, Array.Empty<Type>());
if (mi == null)
return failure;
var caps = mi.Invoke(null, null) as string;
if (String.IsNullOrEmpty(caps))
return failure;
var assm = typeof (ApplyUpdateReferencedAssembly.MethodBody1).Assembly;
var r = ApplyUpdateReferencedAssembly.MethodBody1.StaticMethod1();
if ("OLD STRING" != r)
return failure;
ApplyUpdate(assm);
r = ApplyUpdateReferencedAssembly.MethodBody1.StaticMethod1();
if ("NEW STRING" != r)
return failure;
ApplyUpdate(assm);
r = ApplyUpdateReferencedAssembly.MethodBody1.StaticMethod1();
if ("NEWEST STRING" != r)
return failure;
return success;
}
private static System.Collections.Generic.Dictionary<Assembly, int> assembly_count = new();
internal static void ApplyUpdate (System.Reflection.Assembly assm)
{
int count;
if (!assembly_count.TryGetValue(assm, out count))
count = 1;
else
count++;
assembly_count [assm] = count;
/* FIXME WASM: Location is empty on wasm. Make up a name based on Name */
string basename = assm.Location;
if (basename == "")
basename = assm.GetName().Name + ".dll";
Console.Error.WriteLine($"Apply Delta Update for {basename}, revision {count}");
string dmeta_name = $"{basename}.{count}.dmeta";
string dil_name = $"{basename}.{count}.dil";
byte[] dmeta_data = System.IO.File.ReadAllBytes(dmeta_name);
byte[] dil_data = System.IO.File.ReadAllBytes(dil_name);
byte[] dpdb_data = null; // TODO also use the dpdb data
System.Reflection.Metadata.MetadataUpdater.ApplyUpdate(assm, dmeta_data, dil_data, dpdb_data);
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/TestServer.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.IO.Compression;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public static class TestServer
{
public const string ExpectedResponseBody = "This is the response body.";
public const string FakeServerEndpoint = "http://www.contoso.com/";
public const string FakeSecureServerEndpoint = "https://www.contoso.com/";
public static readonly byte[] ExpectedResponseBodyBytes = Encoding.UTF8.GetBytes(ExpectedResponseBody);
private static MemoryStream requestBody = null;
private static MemoryStream responseBody = null;
private static string responseHeaders = null;
private static double dataAvailablePercentage = 1.0;
public static byte[] RequestBody
{
get
{
return requestBody.ToArray();
}
}
public static byte[] ResponseBody
{
set
{
responseBody.Write(value, 0, value.Length);
responseBody.Position = 0;
}
}
public static string ResponseHeaders
{
get
{
return responseHeaders;
}
set
{
responseHeaders = value;
}
}
public static double DataAvailablePercentage
{
get
{
return dataAvailablePercentage;
}
set
{
dataAvailablePercentage = value;
}
}
public static int DataAvailable
{
get
{
if (responseBody == null)
{
return 0;
}
int totalBytesLeftToRead = (int)(responseBody.Length - responseBody.Position);
int allowedBytesToRead = (int)((double)totalBytesLeftToRead * dataAvailablePercentage);
if (allowedBytesToRead == 0 && totalBytesLeftToRead != 0)
{
allowedBytesToRead = 1;
}
return allowedBytesToRead;
}
}
public static void WriteToRequestBody(IntPtr buffer, uint bufferSize)
{
var bytes = new byte[bufferSize];
Marshal.Copy(buffer, bytes, 0, (int)bufferSize);
requestBody.Write(bytes, 0, (int)bufferSize);
}
public static void ReadFromResponseBody(IntPtr buffer, uint bufferSize, out uint bytesRead)
{
bytesRead = 0;
if (responseBody == null)
{
return;
}
for (var i = 0; i < bufferSize; i++)
{
int data = responseBody.ReadByte();
if (data == -1)
{
return;
}
System.Runtime.InteropServices.Marshal.WriteByte(IntPtr.Add(buffer, i), (byte)data);
bytesRead++;
}
}
public static void SetResponse(DecompressionMethods compressionKind, string responseBody)
{
byte[] responseBodyBytes = Encoding.UTF8.GetBytes(responseBody);
byte[] compressedBytes;
string responseHeadersFormat =
"HTTP/1.1 200 OK\r\n" +
"{0}" +
"Content-Length: {1}\r\n" +
"Content-Type: text/plain; charset=utf-8\r\n" +
"Date: Tue, 08 Jul 2014 20:45:02 GMT\r\n";
if (compressionKind == DecompressionMethods.None)
{
compressedBytes = responseBodyBytes;
}
else
{
compressedBytes = CompressBytes(responseBodyBytes, compressionKind == DecompressionMethods.GZip);
}
ResponseBody = compressedBytes;
string contentEncodingHeader = string.Empty;
if (compressionKind != DecompressionMethods.None)
{
contentEncodingHeader = string.Format("Content-Encoding: {0}\r\n", compressionKind.ToString().ToLower());
}
ResponseHeaders = string.Format(responseHeadersFormat, contentEncodingHeader, compressedBytes.Length);
}
public static void Reset()
{
requestBody = new MemoryStream();
responseBody = new MemoryStream();
responseHeaders = null;
dataAvailablePercentage = 1.0;
}
public static byte[] CompressBytes(byte[] bytes, bool useGZip)
{
using (var memoryStream = new MemoryStream())
{
using (Stream compressedStream = useGZip ?
new GZipStream(memoryStream, CompressionMode.Compress) :
new DeflateStream(memoryStream, CompressionMode.Compress))
{
compressedStream.Write(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public static class TestServer
{
public const string ExpectedResponseBody = "This is the response body.";
public const string FakeServerEndpoint = "http://www.contoso.com/";
public const string FakeSecureServerEndpoint = "https://www.contoso.com/";
public static readonly byte[] ExpectedResponseBodyBytes = Encoding.UTF8.GetBytes(ExpectedResponseBody);
private static MemoryStream requestBody = null;
private static MemoryStream responseBody = null;
private static string responseHeaders = null;
private static double dataAvailablePercentage = 1.0;
public static byte[] RequestBody
{
get
{
return requestBody.ToArray();
}
}
public static byte[] ResponseBody
{
set
{
responseBody.Write(value, 0, value.Length);
responseBody.Position = 0;
}
}
public static string ResponseHeaders
{
get
{
return responseHeaders;
}
set
{
responseHeaders = value;
}
}
public static double DataAvailablePercentage
{
get
{
return dataAvailablePercentage;
}
set
{
dataAvailablePercentage = value;
}
}
public static int DataAvailable
{
get
{
if (responseBody == null)
{
return 0;
}
int totalBytesLeftToRead = (int)(responseBody.Length - responseBody.Position);
int allowedBytesToRead = (int)((double)totalBytesLeftToRead * dataAvailablePercentage);
if (allowedBytesToRead == 0 && totalBytesLeftToRead != 0)
{
allowedBytesToRead = 1;
}
return allowedBytesToRead;
}
}
public static void WriteToRequestBody(IntPtr buffer, uint bufferSize)
{
var bytes = new byte[bufferSize];
Marshal.Copy(buffer, bytes, 0, (int)bufferSize);
requestBody.Write(bytes, 0, (int)bufferSize);
}
public static void ReadFromResponseBody(IntPtr buffer, uint bufferSize, out uint bytesRead)
{
bytesRead = 0;
if (responseBody == null)
{
return;
}
for (var i = 0; i < bufferSize; i++)
{
int data = responseBody.ReadByte();
if (data == -1)
{
return;
}
System.Runtime.InteropServices.Marshal.WriteByte(IntPtr.Add(buffer, i), (byte)data);
bytesRead++;
}
}
public static void SetResponse(DecompressionMethods compressionKind, string responseBody)
{
byte[] responseBodyBytes = Encoding.UTF8.GetBytes(responseBody);
byte[] compressedBytes;
string responseHeadersFormat =
"HTTP/1.1 200 OK\r\n" +
"{0}" +
"Content-Length: {1}\r\n" +
"Content-Type: text/plain; charset=utf-8\r\n" +
"Date: Tue, 08 Jul 2014 20:45:02 GMT\r\n";
if (compressionKind == DecompressionMethods.None)
{
compressedBytes = responseBodyBytes;
}
else
{
compressedBytes = CompressBytes(responseBodyBytes, compressionKind == DecompressionMethods.GZip);
}
ResponseBody = compressedBytes;
string contentEncodingHeader = string.Empty;
if (compressionKind != DecompressionMethods.None)
{
contentEncodingHeader = string.Format("Content-Encoding: {0}\r\n", compressionKind.ToString().ToLower());
}
ResponseHeaders = string.Format(responseHeadersFormat, contentEncodingHeader, compressedBytes.Length);
}
public static void Reset()
{
requestBody = new MemoryStream();
responseBody = new MemoryStream();
responseHeaders = null;
dataAvailablePercentage = 1.0;
}
public static byte[] CompressBytes(byte[] bytes, bool useGZip)
{
using (var memoryStream = new MemoryStream())
{
using (Stream compressedStream = useGZip ?
new GZipStream(memoryStream, CompressionMode.Compress) :
new DeflateStream(memoryStream, CompressionMode.Compress))
{
compressedStream.Write(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/UrlAttributeTests.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 UrlAttributeTests : ValidationAttributeTestBase
{
protected override IEnumerable<TestCase> ValidValues()
{
yield return new TestCase(new UrlAttribute(), null);
yield return new TestCase(new UrlAttribute(), "http://foo.bar");
yield return new TestCase(new UrlAttribute(), "https://foo.bar");
yield return new TestCase(new UrlAttribute(), "ftp://foo.bar");
}
protected override IEnumerable<TestCase> InvalidValues()
{
yield return new TestCase(new UrlAttribute(), "file:///foo.bar");
yield return new TestCase(new UrlAttribute(), "foo.png");
yield return new TestCase(new UrlAttribute(), new object());
}
[Fact]
public static void DataType_CustomDataType_ReturnsExpected()
{
var attribute = new UrlAttribute();
Assert.Equal(DataType.Url, attribute.DataType);
Assert.Null(attribute.CustomDataType);
}
}
}
| // 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 UrlAttributeTests : ValidationAttributeTestBase
{
protected override IEnumerable<TestCase> ValidValues()
{
yield return new TestCase(new UrlAttribute(), null);
yield return new TestCase(new UrlAttribute(), "http://foo.bar");
yield return new TestCase(new UrlAttribute(), "https://foo.bar");
yield return new TestCase(new UrlAttribute(), "ftp://foo.bar");
}
protected override IEnumerable<TestCase> InvalidValues()
{
yield return new TestCase(new UrlAttribute(), "file:///foo.bar");
yield return new TestCase(new UrlAttribute(), "foo.png");
yield return new TestCase(new UrlAttribute(), new object());
}
[Fact]
public static void DataType_CustomDataType_ReturnsExpected()
{
var attribute = new UrlAttribute();
Assert.Equal(DataType.Url, attribute.DataType);
Assert.Null(attribute.CustomDataType);
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Linq.Parallel/tests/QueryOperators/ConcatTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class ConcatTests
{
public static IEnumerable<object[]> ConcatUnorderedData(int[] counts)
{
foreach (int leftCount in counts)
{
foreach (int rightCount in counts)
{
yield return new object[] { leftCount, rightCount };
}
}
}
public static IEnumerable<object[]> ConcatData(int[] counts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(counts.DefaultIfEmpty(Sources.OuterLoopCount), (left, right) => left, counts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
//
// Concat
//
[Theory]
[MemberData(nameof(ConcatUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Concat_Unordered(int leftCount, int rightCount)
{
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
foreach (int i in UnorderedSources.Default(0, leftCount).Concat(UnorderedSources.Default(leftCount, rightCount)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Concat_Unordered_Longrunning()
{
Concat_Unordered(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(ConcatData), new[] { 0, 1, 2, 16 })]
public static void Concat(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
// The ordering of Concat is only guaranteed when both operands are ordered,
// however the current implementation manages to perform ordering if either operand is ordered _in most cases_.
// If this test starts failing, consider revising the operators and mention the change in release notes.
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Concat(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(seen, leftCount + rightCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ConcatData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Concat_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Concat(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(ConcatUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Concat_Unordered_NotPipelined(int leftCount, int rightCount)
{
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
Assert.All(UnorderedSources.Default(leftCount).Concat(UnorderedSources.Default(leftCount, rightCount)).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Concat_Unordered_NotPipelined_Longrunning()
{
Concat_Unordered_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(ConcatData), new[] { 0, 1, 2, 16 })]
public static void Concat_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
// The ordering of Concat is only guaranteed when both operands are ordered,
// however the current implementation manages to perform ordering if either operand is ordered _in most cases_.
// If this test starts failing, consider revising the operators and mention the change in release notes.
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Concat(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(seen, leftCount + rightCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ConcatData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Concat_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Concat_NotPipelined(left, leftCount, right, rightCount);
}
[Fact]
public static void Concat_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Concat(Enumerable.Range(0, 1)));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Concat_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Concat(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Concat(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Concat(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Concat(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Concat_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Concat(ParallelEnumerable.Range(0, 1)));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Concat(null));
}
[Fact]
public static void Concat_UnionSources_PrematureMerges()
{
const int ElementCount = 2048;
ParallelQuery<int> leftQuery = ParallelEnumerable.Range(0, ElementCount / 4).Union(ParallelEnumerable.Range(ElementCount / 4, ElementCount / 4));
ParallelQuery<int> rightQuery = ParallelEnumerable.Range(2 * ElementCount / 4, ElementCount / 4).Union(ParallelEnumerable.Range(3 * ElementCount / 4, ElementCount / 4));
var results = new HashSet<int>(leftQuery.Concat(rightQuery));
Assert.Equal(ElementCount, results.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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class ConcatTests
{
public static IEnumerable<object[]> ConcatUnorderedData(int[] counts)
{
foreach (int leftCount in counts)
{
foreach (int rightCount in counts)
{
yield return new object[] { leftCount, rightCount };
}
}
}
public static IEnumerable<object[]> ConcatData(int[] counts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(counts.DefaultIfEmpty(Sources.OuterLoopCount), (left, right) => left, counts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
//
// Concat
//
[Theory]
[MemberData(nameof(ConcatUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Concat_Unordered(int leftCount, int rightCount)
{
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
foreach (int i in UnorderedSources.Default(0, leftCount).Concat(UnorderedSources.Default(leftCount, rightCount)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Concat_Unordered_Longrunning()
{
Concat_Unordered(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(ConcatData), new[] { 0, 1, 2, 16 })]
public static void Concat(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
// The ordering of Concat is only guaranteed when both operands are ordered,
// however the current implementation manages to perform ordering if either operand is ordered _in most cases_.
// If this test starts failing, consider revising the operators and mention the change in release notes.
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Concat(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(seen, leftCount + rightCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ConcatData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Concat_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Concat(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(ConcatUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Concat_Unordered_NotPipelined(int leftCount, int rightCount)
{
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
Assert.All(UnorderedSources.Default(leftCount).Concat(UnorderedSources.Default(leftCount, rightCount)).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Concat_Unordered_NotPipelined_Longrunning()
{
Concat_Unordered_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(ConcatData), new[] { 0, 1, 2, 16 })]
public static void Concat_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
// The ordering of Concat is only guaranteed when both operands are ordered,
// however the current implementation manages to perform ordering if either operand is ordered _in most cases_.
// If this test starts failing, consider revising the operators and mention the change in release notes.
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Concat(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(seen, leftCount + rightCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ConcatData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Concat_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Concat_NotPipelined(left, leftCount, right, rightCount);
}
[Fact]
public static void Concat_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Concat(Enumerable.Range(0, 1)));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Concat_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Concat(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Concat(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Concat(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Concat(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Concat_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Concat(ParallelEnumerable.Range(0, 1)));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Concat(null));
}
[Fact]
public static void Concat_UnionSources_PrematureMerges()
{
const int ElementCount = 2048;
ParallelQuery<int> leftQuery = ParallelEnumerable.Range(0, ElementCount / 4).Union(ParallelEnumerable.Range(ElementCount / 4, ElementCount / 4));
ParallelQuery<int> rightQuery = ParallelEnumerable.Range(2 * ElementCount / 4, ElementCount / 4).Union(ParallelEnumerable.Range(3 * ElementCount / 4, ElementCount / 4));
var results = new HashSet<int>(leftQuery.Concat(rightQuery));
Assert.Equal(ElementCount, results.Count);
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/User.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Principal;
namespace System.DirectoryServices.AccountManagement
{
[DirectoryRdnPrefix("CN")]
public class UserPrincipal : AuthenticablePrincipal
{
//
// Public constructors
//
public UserPrincipal(PrincipalContext context) : base(context)
{
if (context == null)
throw new ArgumentException(SR.NullArguments);
this.ContextRaw = context;
this.unpersisted = true;
}
public UserPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context)
{
if (samAccountName == null || password == null)
throw new ArgumentException(SR.NullArguments);
if (Context.ContextType != ContextType.ApplicationDirectory)
this.SamAccountName = samAccountName;
this.Name = samAccountName;
this.SetPassword(password);
this.Enabled = enabled;
}
//
// Public properties
//
// GivenName
private string _givenName; // the actual property value
private LoadState _givenNameChanged = LoadState.NotSet; // change-tracking
public string GivenName
{
get
{
return HandleGet<string>(ref _givenName, PropertyNames.UserGivenName, ref _givenNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserGivenName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _givenName, value, ref _givenNameChanged,
PropertyNames.UserGivenName);
}
}
// MiddleName
private string _middleName; // the actual property value
private LoadState _middleNameChanged = LoadState.NotSet; // change-tracking
public string MiddleName
{
get
{
return HandleGet<string>(ref _middleName, PropertyNames.UserMiddleName, ref _middleNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserMiddleName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _middleName, value, ref _middleNameChanged,
PropertyNames.UserMiddleName);
}
}
// Surname
private string _surname; // the actual property value
private LoadState _surnameChanged = LoadState.NotSet; // change-tracking
public string Surname
{
get
{
return HandleGet<string>(ref _surname, PropertyNames.UserSurname, ref _surnameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserSurname))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _surname, value, ref _surnameChanged,
PropertyNames.UserSurname);
}
}
// EmailAddress
private string _emailAddress; // the actual property value
private LoadState _emailAddressChanged = LoadState.NotSet; // change-tracking
public string EmailAddress
{
get
{
return HandleGet<string>(ref _emailAddress, PropertyNames.UserEmailAddress, ref _emailAddressChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmailAddress))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _emailAddress, value, ref _emailAddressChanged,
PropertyNames.UserEmailAddress);
}
}
// VoiceTelephoneNumber
private string _voiceTelephoneNumber; // the actual property value
private LoadState _voiceTelephoneNumberChanged = LoadState.NotSet; // change-tracking
public string VoiceTelephoneNumber
{
get
{
return HandleGet<string>(ref _voiceTelephoneNumber, PropertyNames.UserVoiceTelephoneNumber, ref _voiceTelephoneNumberChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserVoiceTelephoneNumber))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _voiceTelephoneNumber, value, ref _voiceTelephoneNumberChanged,
PropertyNames.UserVoiceTelephoneNumber);
}
}
// EmployeeId
private string _employeeID; // the actual property value
private LoadState _employeeIDChanged = LoadState.NotSet; // change-tracking
public string EmployeeId
{
get
{
return HandleGet<string>(ref _employeeID, PropertyNames.UserEmployeeID, ref _employeeIDChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmployeeID))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _employeeID, value, ref _employeeIDChanged,
PropertyNames.UserEmployeeID);
}
}
public override AdvancedFilters AdvancedSearchFilter { get { return rosf; } }
public static UserPrincipal Current
{
get
{
PrincipalContext context;
// Get the correct PrincipalContext to query against, depending on whether we're running
// as a local or domain user
if (Utils.IsSamUser())
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is local user");
context = new PrincipalContext(ContextType.Machine);
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is not local user");
context = new PrincipalContext(ContextType.Domain);
}
// Construct a query for the current user, using a SID IdentityClaim
IntPtr pSid = IntPtr.Zero;
UserPrincipal user = null;
try
{
pSid = Utils.GetCurrentUserSid();
byte[] sid = Utils.ConvertNativeSidToByteArray(pSid);
SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: using SID " + sidObj.ToString());
user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, sidObj.ToString());
}
finally
{
if (pSid != IntPtr.Zero)
System.Runtime.InteropServices.Marshal.FreeHGlobal(pSid);
}
// We're running as the user, we know they must exist, but perhaps we don't have access
// to their user object
if (user == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "User", "Current: found no user");
throw new NoMatchingPrincipalException(SR.UserCouldNotFindCurrent);
}
return user;
}
}
//
// Public methods
//
public static new PrincipalSearchResult<UserPrincipal> FindByLockoutTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByLockoutTime<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByLogonTime<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByExpirationTime<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type)
{
return FindByBadPasswordAttempt<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByPasswordSetTime<UserPrincipal>(context, time, type);
}
public static new UserPrincipal FindByIdentity(PrincipalContext context, string identityValue)
{
return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityValue);
}
public static new UserPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
{
return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityType, identityValue);
}
public PrincipalSearchResult<Principal> GetAuthorizationGroups()
{
return new PrincipalSearchResult<Principal>(GetAuthorizationGroupsHelper());
}
//
// Internal "constructor": Used for constructing Users returned by a query
//
internal static UserPrincipal MakeUser(PrincipalContext ctx)
{
UserPrincipal u = new UserPrincipal(ctx);
u.unpersisted = false;
return u;
}
//
// Private implementation
//
private ResultSet GetAuthorizationGroupsHelper()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Unpersisted principals are not members of any group
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: unpersisted, using EmptySet");
return new EmptySet();
}
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"User",
"GetAuthorizationGroupsHelper: retrieving AZ groups from StoreCtx of type=" + storeCtx.GetType().ToString() +
", base path=" + storeCtx.BasePath);
ResultSet resultSet = storeCtx.GetGroupsMemberOfAZ(this);
return resultSet;
}
//
// Load/Store implementation
//
//
// Loading with query results
//
internal override void LoadValueIntoProperty(string propertyName, object value)
{
if (value == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value= null");
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString());
}
switch (propertyName)
{
case (PropertyNames.UserGivenName):
_givenName = (string)value;
_givenNameChanged = LoadState.Loaded;
break;
case (PropertyNames.UserMiddleName):
_middleName = (string)value;
_middleNameChanged = LoadState.Loaded;
break;
case (PropertyNames.UserSurname):
_surname = (string)value;
_surnameChanged = LoadState.Loaded;
break;
case (PropertyNames.UserEmailAddress):
_emailAddress = (string)value;
_emailAddressChanged = LoadState.Loaded;
break;
case (PropertyNames.UserVoiceTelephoneNumber):
_voiceTelephoneNumber = (string)value;
_voiceTelephoneNumberChanged = LoadState.Loaded;
break;
case (PropertyNames.UserEmployeeID):
_employeeID = (string)value;
_employeeIDChanged = LoadState.Loaded;
break;
default:
base.LoadValueIntoProperty(propertyName, value);
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
internal override bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetChangeStatusForProperty: name=" + propertyName);
return propertyName switch
{
PropertyNames.UserGivenName => _givenNameChanged == LoadState.Changed,
PropertyNames.UserMiddleName => _middleNameChanged == LoadState.Changed,
PropertyNames.UserSurname => _surnameChanged == LoadState.Changed,
PropertyNames.UserEmailAddress => _emailAddressChanged == LoadState.Changed,
PropertyNames.UserVoiceTelephoneNumber => _voiceTelephoneNumberChanged == LoadState.Changed,
PropertyNames.UserEmployeeID => _employeeIDChanged == LoadState.Changed,
_ => base.GetChangeStatusForProperty(propertyName),
};
}
// Given a property name, returns the current value for the property.
internal override object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetValueForProperty: name=" + propertyName);
return propertyName switch
{
PropertyNames.UserGivenName => _givenName,
PropertyNames.UserMiddleName => _middleName,
PropertyNames.UserSurname => _surname,
PropertyNames.UserEmailAddress => _emailAddress,
PropertyNames.UserVoiceTelephoneNumber => _voiceTelephoneNumber,
PropertyNames.UserEmployeeID => _employeeID,
_ => base.GetValueForProperty(propertyName),
};
}
// Reset all change-tracking status for all properties on the object to "unchanged".
internal override void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "ResetAllChangeStatus");
_givenNameChanged = (_givenNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_middleNameChanged = (_middleNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_surnameChanged = (_surnameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_emailAddressChanged = (_emailAddressChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_voiceTelephoneNumberChanged = (_voiceTelephoneNumberChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_employeeIDChanged = (_employeeIDChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
base.ResetAllChangeStatus();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Principal;
namespace System.DirectoryServices.AccountManagement
{
[DirectoryRdnPrefix("CN")]
public class UserPrincipal : AuthenticablePrincipal
{
//
// Public constructors
//
public UserPrincipal(PrincipalContext context) : base(context)
{
if (context == null)
throw new ArgumentException(SR.NullArguments);
this.ContextRaw = context;
this.unpersisted = true;
}
public UserPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context)
{
if (samAccountName == null || password == null)
throw new ArgumentException(SR.NullArguments);
if (Context.ContextType != ContextType.ApplicationDirectory)
this.SamAccountName = samAccountName;
this.Name = samAccountName;
this.SetPassword(password);
this.Enabled = enabled;
}
//
// Public properties
//
// GivenName
private string _givenName; // the actual property value
private LoadState _givenNameChanged = LoadState.NotSet; // change-tracking
public string GivenName
{
get
{
return HandleGet<string>(ref _givenName, PropertyNames.UserGivenName, ref _givenNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserGivenName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _givenName, value, ref _givenNameChanged,
PropertyNames.UserGivenName);
}
}
// MiddleName
private string _middleName; // the actual property value
private LoadState _middleNameChanged = LoadState.NotSet; // change-tracking
public string MiddleName
{
get
{
return HandleGet<string>(ref _middleName, PropertyNames.UserMiddleName, ref _middleNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserMiddleName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _middleName, value, ref _middleNameChanged,
PropertyNames.UserMiddleName);
}
}
// Surname
private string _surname; // the actual property value
private LoadState _surnameChanged = LoadState.NotSet; // change-tracking
public string Surname
{
get
{
return HandleGet<string>(ref _surname, PropertyNames.UserSurname, ref _surnameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserSurname))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _surname, value, ref _surnameChanged,
PropertyNames.UserSurname);
}
}
// EmailAddress
private string _emailAddress; // the actual property value
private LoadState _emailAddressChanged = LoadState.NotSet; // change-tracking
public string EmailAddress
{
get
{
return HandleGet<string>(ref _emailAddress, PropertyNames.UserEmailAddress, ref _emailAddressChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmailAddress))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _emailAddress, value, ref _emailAddressChanged,
PropertyNames.UserEmailAddress);
}
}
// VoiceTelephoneNumber
private string _voiceTelephoneNumber; // the actual property value
private LoadState _voiceTelephoneNumberChanged = LoadState.NotSet; // change-tracking
public string VoiceTelephoneNumber
{
get
{
return HandleGet<string>(ref _voiceTelephoneNumber, PropertyNames.UserVoiceTelephoneNumber, ref _voiceTelephoneNumberChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserVoiceTelephoneNumber))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _voiceTelephoneNumber, value, ref _voiceTelephoneNumberChanged,
PropertyNames.UserVoiceTelephoneNumber);
}
}
// EmployeeId
private string _employeeID; // the actual property value
private LoadState _employeeIDChanged = LoadState.NotSet; // change-tracking
public string EmployeeId
{
get
{
return HandleGet<string>(ref _employeeID, PropertyNames.UserEmployeeID, ref _employeeIDChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmployeeID))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _employeeID, value, ref _employeeIDChanged,
PropertyNames.UserEmployeeID);
}
}
public override AdvancedFilters AdvancedSearchFilter { get { return rosf; } }
public static UserPrincipal Current
{
get
{
PrincipalContext context;
// Get the correct PrincipalContext to query against, depending on whether we're running
// as a local or domain user
if (Utils.IsSamUser())
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is local user");
context = new PrincipalContext(ContextType.Machine);
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is not local user");
context = new PrincipalContext(ContextType.Domain);
}
// Construct a query for the current user, using a SID IdentityClaim
IntPtr pSid = IntPtr.Zero;
UserPrincipal user = null;
try
{
pSid = Utils.GetCurrentUserSid();
byte[] sid = Utils.ConvertNativeSidToByteArray(pSid);
SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: using SID " + sidObj.ToString());
user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, sidObj.ToString());
}
finally
{
if (pSid != IntPtr.Zero)
System.Runtime.InteropServices.Marshal.FreeHGlobal(pSid);
}
// We're running as the user, we know they must exist, but perhaps we don't have access
// to their user object
if (user == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "User", "Current: found no user");
throw new NoMatchingPrincipalException(SR.UserCouldNotFindCurrent);
}
return user;
}
}
//
// Public methods
//
public static new PrincipalSearchResult<UserPrincipal> FindByLockoutTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByLockoutTime<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByLogonTime<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByExpirationTime<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type)
{
return FindByBadPasswordAttempt<UserPrincipal>(context, time, type);
}
public static new PrincipalSearchResult<UserPrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type)
{
return FindByPasswordSetTime<UserPrincipal>(context, time, type);
}
public static new UserPrincipal FindByIdentity(PrincipalContext context, string identityValue)
{
return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityValue);
}
public static new UserPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
{
return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityType, identityValue);
}
public PrincipalSearchResult<Principal> GetAuthorizationGroups()
{
return new PrincipalSearchResult<Principal>(GetAuthorizationGroupsHelper());
}
//
// Internal "constructor": Used for constructing Users returned by a query
//
internal static UserPrincipal MakeUser(PrincipalContext ctx)
{
UserPrincipal u = new UserPrincipal(ctx);
u.unpersisted = false;
return u;
}
//
// Private implementation
//
private ResultSet GetAuthorizationGroupsHelper()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Unpersisted principals are not members of any group
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: unpersisted, using EmptySet");
return new EmptySet();
}
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"User",
"GetAuthorizationGroupsHelper: retrieving AZ groups from StoreCtx of type=" + storeCtx.GetType().ToString() +
", base path=" + storeCtx.BasePath);
ResultSet resultSet = storeCtx.GetGroupsMemberOfAZ(this);
return resultSet;
}
//
// Load/Store implementation
//
//
// Loading with query results
//
internal override void LoadValueIntoProperty(string propertyName, object value)
{
if (value == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value= null");
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString());
}
switch (propertyName)
{
case (PropertyNames.UserGivenName):
_givenName = (string)value;
_givenNameChanged = LoadState.Loaded;
break;
case (PropertyNames.UserMiddleName):
_middleName = (string)value;
_middleNameChanged = LoadState.Loaded;
break;
case (PropertyNames.UserSurname):
_surname = (string)value;
_surnameChanged = LoadState.Loaded;
break;
case (PropertyNames.UserEmailAddress):
_emailAddress = (string)value;
_emailAddressChanged = LoadState.Loaded;
break;
case (PropertyNames.UserVoiceTelephoneNumber):
_voiceTelephoneNumber = (string)value;
_voiceTelephoneNumberChanged = LoadState.Loaded;
break;
case (PropertyNames.UserEmployeeID):
_employeeID = (string)value;
_employeeIDChanged = LoadState.Loaded;
break;
default:
base.LoadValueIntoProperty(propertyName, value);
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
internal override bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetChangeStatusForProperty: name=" + propertyName);
return propertyName switch
{
PropertyNames.UserGivenName => _givenNameChanged == LoadState.Changed,
PropertyNames.UserMiddleName => _middleNameChanged == LoadState.Changed,
PropertyNames.UserSurname => _surnameChanged == LoadState.Changed,
PropertyNames.UserEmailAddress => _emailAddressChanged == LoadState.Changed,
PropertyNames.UserVoiceTelephoneNumber => _voiceTelephoneNumberChanged == LoadState.Changed,
PropertyNames.UserEmployeeID => _employeeIDChanged == LoadState.Changed,
_ => base.GetChangeStatusForProperty(propertyName),
};
}
// Given a property name, returns the current value for the property.
internal override object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetValueForProperty: name=" + propertyName);
return propertyName switch
{
PropertyNames.UserGivenName => _givenName,
PropertyNames.UserMiddleName => _middleName,
PropertyNames.UserSurname => _surname,
PropertyNames.UserEmailAddress => _emailAddress,
PropertyNames.UserVoiceTelephoneNumber => _voiceTelephoneNumber,
PropertyNames.UserEmployeeID => _employeeID,
_ => base.GetValueForProperty(propertyName),
};
}
// Reset all change-tracking status for all properties on the object to "unchanged".
internal override void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "ResetAllChangeStatus");
_givenNameChanged = (_givenNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_middleNameChanged = (_middleNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_surnameChanged = (_surnameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_emailAddressChanged = (_emailAddressChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_voiceTelephoneNumberChanged = (_voiceTelephoneNumberChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_employeeIDChanged = (_employeeIDChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
base.ResetAllChangeStatus();
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/Interop/PInvoke/Generics/GenericsTest.NullableD.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Xunit;
unsafe partial class GenericsNative
{
[DllImport(nameof(GenericsNative))]
public static extern double? GetNullableD(bool hasValue, double value);
[DllImport(nameof(GenericsNative))]
public static extern void GetNullableDOut(bool hasValue, double value, out double? pValue);
[DllImport(nameof(GenericsNative), EntryPoint = "GetNullableDPtr")]
public static extern ref readonly double? GetNullableDRef(bool hasValue, double value);
[DllImport(nameof(GenericsNative))]
public static extern double? AddNullableD(double? lhs, double? rhs);
[DllImport(nameof(GenericsNative))]
public static extern double? AddNullableDs([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] double?[] pValues, int count);
[DllImport(nameof(GenericsNative))]
public static extern double? AddNullableDs(in double? pValues, int count);
}
unsafe partial class GenericsTest
{
private static void TestNullableD()
{
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableD(true, 1.0));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableDOut(true, 1.0, out double? value3));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableD(default, default));
double?[] values = new double?[] {
default,
default,
default,
default,
default
};
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableDs(values, values.Length));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableDs(in values[0], values.Length));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Xunit;
unsafe partial class GenericsNative
{
[DllImport(nameof(GenericsNative))]
public static extern double? GetNullableD(bool hasValue, double value);
[DllImport(nameof(GenericsNative))]
public static extern void GetNullableDOut(bool hasValue, double value, out double? pValue);
[DllImport(nameof(GenericsNative), EntryPoint = "GetNullableDPtr")]
public static extern ref readonly double? GetNullableDRef(bool hasValue, double value);
[DllImport(nameof(GenericsNative))]
public static extern double? AddNullableD(double? lhs, double? rhs);
[DllImport(nameof(GenericsNative))]
public static extern double? AddNullableDs([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] double?[] pValues, int count);
[DllImport(nameof(GenericsNative))]
public static extern double? AddNullableDs(in double? pValues, int count);
}
unsafe partial class GenericsTest
{
private static void TestNullableD()
{
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableD(true, 1.0));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableDOut(true, 1.0, out double? value3));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableD(default, default));
double?[] values = new double?[] {
default,
default,
default,
default,
default
};
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableDs(values, values.Length));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableDs(in values[0], values.Length));
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Reflection.Emit/tests/ConstructorBuilder/ConstructorBuilderToString.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.Reflection.Emit.Tests
{
public class ConstructorBuilderToString
{
[Fact]
public void ToString_NullRequiredOptionalCustomModifiers()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
Type[] parameterTypes = new Type[] { typeof(int), typeof(double) };
ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameterTypes, null, null);
Assert.StartsWith("Name: .ctor", constructor.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NoRequiredOptionalCustomModifiers()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
Type[] parameterTypes = new Type[] { typeof(int), typeof(double) };
ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameterTypes);
Assert.StartsWith("Name: .ctor", constructor.ToString());
}
}
}
| // 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.Reflection.Emit.Tests
{
public class ConstructorBuilderToString
{
[Fact]
public void ToString_NullRequiredOptionalCustomModifiers()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
Type[] parameterTypes = new Type[] { typeof(int), typeof(double) };
ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameterTypes, null, null);
Assert.StartsWith("Name: .ctor", constructor.ToString());
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)]
public void ToString_NoRequiredOptionalCustomModifiers()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
Type[] parameterTypes = new Type[] { typeof(int), typeof(double) };
ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameterTypes);
Assert.StartsWith("Name: .ctor", constructor.ToString());
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace Microsoft.Extensions.DependencyModel
{
public class DependencyContextJsonReader : IDependencyContextReader
{
private const int UnseekableStreamInitialRentSize = 4096;
private static ReadOnlySpan<byte> Utf8Bom => new byte[] { 0xEF, 0xBB, 0xBF };
private readonly IDictionary<string, string> _stringPool = new Dictionary<string, string>();
public DependencyContext Read(Stream stream!!)
{
ArraySegment<byte> buffer = ReadToEnd(stream);
try
{
return Read(new Utf8JsonReader(buffer, isFinalBlock: true, state: default));
}
finally
{
// Holds document content, clear it before returning it.
buffer.AsSpan().Clear();
ArrayPool<byte>.Shared.Return(buffer.Array!);
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_stringPool.Clear();
}
}
public void Dispose()
{
Dispose(true);
}
// Borrowed from https://github.com/dotnet/corefx/blob/b8bc4ff80c5f7baa681e8a569d367356957ba78a/src/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs#L290-L362
private static ArraySegment<byte> ReadToEnd(Stream stream)
{
int written = 0;
byte[]? rented = null;
ReadOnlySpan<byte> utf8Bom = Utf8Bom;
try
{
if (stream.CanSeek)
{
// Ask for 1 more than the length to avoid resizing later,
// which is unnecessary in the common case where the stream length doesn't change.
long expectedLength = Math.Max(utf8Bom.Length, stream.Length - stream.Position) + 1;
rented = ArrayPool<byte>.Shared.Rent(checked((int)expectedLength));
}
else
{
rented = ArrayPool<byte>.Shared.Rent(UnseekableStreamInitialRentSize);
}
int lastRead;
// Read up to 3 bytes to see if it's the UTF-8 BOM, for parity with the behavior
// of StreamReader..ctor(Stream).
do
{
// No need for checking for growth, the minimal rent sizes both guarantee it'll fit.
Debug.Assert(rented.Length >= utf8Bom.Length);
lastRead = stream.Read(
rented,
written,
utf8Bom.Length - written);
written += lastRead;
} while (lastRead > 0 && written < utf8Bom.Length);
// If we have 3 bytes, and they're the BOM, reset the write position to 0.
if (written == utf8Bom.Length &&
utf8Bom.SequenceEqual(rented.AsSpan(0, utf8Bom.Length)))
{
written = 0;
}
do
{
if (rented.Length == written)
{
byte[] toReturn = rented;
rented = ArrayPool<byte>.Shared.Rent(checked(toReturn.Length * 2));
Buffer.BlockCopy(toReturn, 0, rented, 0, toReturn.Length);
// Holds document content, clear it.
ArrayPool<byte>.Shared.Return(toReturn, clearArray: true);
}
lastRead = stream.Read(rented, written, rented.Length - written);
written += lastRead;
} while (lastRead > 0);
return new ArraySegment<byte>(rented, 0, written);
}
catch
{
if (rented != null)
{
// Holds document content, clear it before returning it.
rented.AsSpan(0, written).Clear();
ArrayPool<byte>.Shared.Return(rented);
}
throw;
}
}
private DependencyContext Read(Utf8JsonReader reader)
{
reader.ReadStartObject();
string runtime = string.Empty;
string framework = string.Empty;
bool isPortable = true;
string? runtimeTargetName = null;
string? runtimeSignature = null;
CompilationOptions? compilationOptions = null;
List<Target>? targets = null;
Dictionary<string, LibraryStub>? libraryStubs = null;
List<RuntimeFallbacks>? runtimeFallbacks = null;
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.RuntimeTargetPropertyName:
ReadRuntimeTarget(ref reader, out runtimeTargetName, out runtimeSignature);
break;
case DependencyContextStrings.CompilationOptionsPropertName:
compilationOptions = ReadCompilationOptions(ref reader);
break;
case DependencyContextStrings.TargetsPropertyName:
targets = ReadTargets(ref reader);
break;
case DependencyContextStrings.LibrariesPropertyName:
libraryStubs = ReadLibraries(ref reader);
break;
case DependencyContextStrings.RuntimesPropertyName:
runtimeFallbacks = ReadRuntimes(ref reader);
break;
default:
reader.Skip();
break;
}
}
if (compilationOptions == null)
{
compilationOptions = CompilationOptions.Default;
}
Target? runtimeTarget = SelectRuntimeTarget(targets, runtimeTargetName);
runtimeTargetName = runtimeTarget?.Name;
if (runtimeTargetName != null)
{
int separatorIndex = runtimeTargetName.IndexOf(DependencyContextStrings.VersionSeparator);
if (separatorIndex > -1 && separatorIndex < runtimeTargetName.Length)
{
runtime = runtimeTargetName.Substring(separatorIndex + 1);
framework = runtimeTargetName.Substring(0, separatorIndex);
isPortable = false;
}
else
{
framework = runtimeTargetName;
}
}
Target? compileTarget = null;
Target? ridlessTarget = targets.FirstOrDefault(t => !IsRuntimeTarget(t.Name));
if (ridlessTarget != null)
{
compileTarget = ridlessTarget;
if (runtimeTarget == null)
{
runtimeTarget = compileTarget;
framework = ridlessTarget.Name;
}
}
if (runtimeTarget == null)
{
throw new FormatException(SR.NoRuntimeTarget);
}
return new DependencyContext(
new TargetInfo(framework, runtime, runtimeSignature, isPortable),
compilationOptions,
CreateLibraries(compileTarget?.Libraries, false, libraryStubs).Cast<CompilationLibrary>().ToArray(),
CreateLibraries(runtimeTarget.Libraries, true, libraryStubs).Cast<RuntimeLibrary>().ToArray(),
runtimeFallbacks ?? Enumerable.Empty<RuntimeFallbacks>());
}
private static Target? SelectRuntimeTarget([NotNull] List<Target>? targets, string? runtimeTargetName)
{
Target? target;
if (targets == null || targets.Count == 0)
{
throw new FormatException(SR.NoTargetsSection);
}
if (!string.IsNullOrEmpty(runtimeTargetName))
{
target = targets.FirstOrDefault(t => t.Name == runtimeTargetName);
if (target == null)
{
throw new FormatException(SR.Format(SR.TargetNotFound, runtimeTargetName));
}
}
else
{
target = targets.FirstOrDefault(t => IsRuntimeTarget(t.Name));
}
return target;
}
private static bool IsRuntimeTarget(string name)
{
return name.Contains(DependencyContextStrings.VersionSeparator);
}
private static void ReadRuntimeTarget(ref Utf8JsonReader reader, out string? runtimeTargetName, out string? runtimeSignature)
{
runtimeTargetName = null;
runtimeSignature = null;
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
switch (propertyName)
{
case DependencyContextStrings.RuntimeTargetNamePropertyName:
runtimeTargetName = propertyValue;
break;
case DependencyContextStrings.RuntimeTargetSignaturePropertyName:
runtimeSignature = propertyValue;
break;
}
}
reader.CheckEndObject();
}
private static CompilationOptions ReadCompilationOptions(ref Utf8JsonReader reader)
{
IEnumerable<string?>? defines = null;
string? languageVersion = null;
string? platform = null;
bool? allowUnsafe = null;
bool? warningsAsErrors = null;
bool? optimize = null;
string? keyFile = null;
bool? delaySign = null;
bool? publicSign = null;
string? debugType = null;
bool? emitEntryPoint = null;
bool? generateXmlDocumentation = null;
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.DefinesPropertyName:
defines = reader.ReadStringArray();
break;
case DependencyContextStrings.LanguageVersionPropertyName:
languageVersion = reader.ReadAsString();
break;
case DependencyContextStrings.PlatformPropertyName:
platform = reader.ReadAsString();
break;
case DependencyContextStrings.AllowUnsafePropertyName:
allowUnsafe = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.WarningsAsErrorsPropertyName:
warningsAsErrors = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.OptimizePropertyName:
optimize = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.KeyFilePropertyName:
keyFile = reader.ReadAsString();
break;
case DependencyContextStrings.DelaySignPropertyName:
delaySign = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.PublicSignPropertyName:
publicSign = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.DebugTypePropertyName:
debugType = reader.ReadAsString();
break;
case DependencyContextStrings.EmitEntryPointPropertyName:
emitEntryPoint = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.GenerateXmlDocumentationPropertyName:
generateXmlDocumentation = reader.ReadAsNullableBoolean();
break;
default:
reader.Skip();
break;
}
}
reader.CheckEndObject();
return new CompilationOptions(
defines ?? Enumerable.Empty<string?>(),
languageVersion,
platform,
allowUnsafe,
warningsAsErrors,
optimize,
keyFile,
delaySign,
publicSign,
debugType,
emitEntryPoint,
generateXmlDocumentation);
}
private List<Target> ReadTargets(ref Utf8JsonReader reader)
{
reader.ReadStartObject();
var targets = new List<Target>();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? targetName = reader.GetString();
if (string.IsNullOrEmpty(targetName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(targetName)));
}
targets.Add(ReadTarget(ref reader, targetName));
}
reader.CheckEndObject();
return targets;
}
private Target ReadTarget(ref Utf8JsonReader reader, string targetName)
{
reader.ReadStartObject();
var libraries = new List<TargetLibrary>();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? targetLibraryName = reader.GetString();
if (string.IsNullOrEmpty(targetLibraryName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(targetLibraryName)));
}
libraries.Add(ReadTargetLibrary(ref reader, targetLibraryName));
}
reader.CheckEndObject();
return new Target(targetName, libraries);
}
private TargetLibrary ReadTargetLibrary(ref Utf8JsonReader reader, string targetLibraryName)
{
IEnumerable<Dependency>? dependencies = null;
List<RuntimeFile>? runtimes = null;
List<RuntimeFile>? natives = null;
List<string>? compilations = null;
List<RuntimeTargetEntryStub>? runtimeTargets = null;
List<ResourceAssembly>? resources = null;
bool? compileOnly = null;
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.DependenciesPropertyName:
dependencies = ReadTargetLibraryDependencies(ref reader);
break;
case DependencyContextStrings.RuntimeAssembliesKey:
runtimes = ReadRuntimeFiles(ref reader);
break;
case DependencyContextStrings.NativeLibrariesKey:
natives = ReadRuntimeFiles(ref reader);
break;
case DependencyContextStrings.CompileTimeAssembliesKey:
compilations = ReadPropertyNames(ref reader);
break;
case DependencyContextStrings.RuntimeTargetsPropertyName:
runtimeTargets = ReadTargetLibraryRuntimeTargets(ref reader);
break;
case DependencyContextStrings.ResourceAssembliesPropertyName:
resources = ReadTargetLibraryResources(ref reader);
break;
case DependencyContextStrings.CompilationOnlyPropertyName:
compileOnly = reader.ReadAsNullableBoolean();
break;
default:
reader.Skip();
break;
}
}
reader.CheckEndObject();
return new TargetLibrary()
{
Name = targetLibraryName,
Dependencies = dependencies ?? Enumerable.Empty<Dependency>(),
Runtimes = runtimes,
Natives = natives,
Compilations = compilations,
RuntimeTargets = runtimeTargets,
Resources = resources,
CompileOnly = compileOnly
};
}
private IEnumerable<Dependency> ReadTargetLibraryDependencies(ref Utf8JsonReader reader)
{
var dependencies = new List<Dependency>();
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? name, out string? version))
{
if (string.IsNullOrEmpty(name))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(name)));
}
if (string.IsNullOrEmpty(version))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(version)));
}
dependencies.Add(new Dependency(Pool(name), Pool(version)));
}
reader.CheckEndObject();
return dependencies;
}
private static List<string> ReadPropertyNames(ref Utf8JsonReader reader)
{
var runtimes = new List<string>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? libraryName = reader.GetString();
if (string.IsNullOrEmpty(libraryName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(libraryName)));
}
reader.Skip();
runtimes.Add(libraryName);
}
reader.CheckEndObject();
return runtimes;
}
private static List<RuntimeFile> ReadRuntimeFiles(ref Utf8JsonReader reader)
{
var runtimeFiles = new List<RuntimeFile>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? assemblyVersion = null;
string? fileVersion = null;
string? path = reader.GetString();
if (string.IsNullOrEmpty(path))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(path)));
}
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
switch (propertyName)
{
case DependencyContextStrings.AssemblyVersionPropertyName:
assemblyVersion = propertyValue;
break;
case DependencyContextStrings.FileVersionPropertyName:
fileVersion = propertyValue;
break;
}
}
reader.CheckEndObject();
runtimeFiles.Add(new RuntimeFile(path, assemblyVersion, fileVersion));
}
reader.CheckEndObject();
return runtimeFiles;
}
private List<RuntimeTargetEntryStub> ReadTargetLibraryRuntimeTargets(ref Utf8JsonReader reader)
{
var runtimeTargets = new List<RuntimeTargetEntryStub>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? runtimePath = reader.GetString();
if (string.IsNullOrEmpty(runtimePath))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(runtimePath)));
}
var runtimeTarget = new RuntimeTargetEntryStub
{
Path = runtimePath
};
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
switch (propertyName)
{
case DependencyContextStrings.RidPropertyName:
runtimeTarget.Rid = Pool(propertyValue);
break;
case DependencyContextStrings.AssetTypePropertyName:
runtimeTarget.Type = Pool(propertyValue);
break;
case DependencyContextStrings.AssemblyVersionPropertyName:
runtimeTarget.AssemblyVersion = propertyValue;
break;
case DependencyContextStrings.FileVersionPropertyName:
runtimeTarget.FileVersion = propertyValue;
break;
}
}
reader.CheckEndObject();
runtimeTargets.Add(runtimeTarget);
}
reader.CheckEndObject();
return runtimeTargets;
}
private List<ResourceAssembly> ReadTargetLibraryResources(ref Utf8JsonReader reader)
{
var resources = new List<ResourceAssembly>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? path = reader.GetString();
if (string.IsNullOrEmpty(path))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(path)));
}
string? locale = null;
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
if (propertyName == DependencyContextStrings.LocalePropertyName)
{
locale = propertyValue;
}
}
reader.CheckEndObject();
if (locale != null)
{
resources.Add(new ResourceAssembly(path, Pool(locale)));
}
}
reader.CheckEndObject();
return resources;
}
private Dictionary<string, LibraryStub> ReadLibraries(ref Utf8JsonReader reader)
{
var libraries = new Dictionary<string, LibraryStub>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? libraryName = reader.GetString();
if (string.IsNullOrEmpty(libraryName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(libraryName)));
}
libraries.Add(Pool(libraryName), ReadOneLibrary(ref reader));
}
reader.CheckEndObject();
return libraries;
}
private LibraryStub ReadOneLibrary(ref Utf8JsonReader reader)
{
string? hash = null;
string? type = null;
bool serviceable = false;
string? path = null;
string? hashPath = null;
string? runtimeStoreManifestName = null;
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.Sha512PropertyName:
hash = reader.ReadAsString();
break;
case DependencyContextStrings.TypePropertyName:
type = reader.ReadAsString();
break;
case DependencyContextStrings.ServiceablePropertyName:
serviceable = reader.ReadAsBoolean(defaultValue: false);
break;
case DependencyContextStrings.PathPropertyName:
path = reader.ReadAsString();
break;
case DependencyContextStrings.HashPathPropertyName:
hashPath = reader.ReadAsString();
break;
case DependencyContextStrings.RuntimeStoreManifestPropertyName:
runtimeStoreManifestName = reader.ReadAsString();
break;
default:
reader.Skip();
break;
}
}
reader.CheckEndObject();
if (string.IsNullOrEmpty(type))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(type)));
}
return new LibraryStub()
{
Hash = hash,
Type = Pool(type),
Serviceable = serviceable,
Path = path,
HashPath = hashPath,
RuntimeStoreManifestName = runtimeStoreManifestName
};
}
private static List<RuntimeFallbacks> ReadRuntimes(ref Utf8JsonReader reader)
{
var runtimeFallbacks = new List<RuntimeFallbacks>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? runtime = reader.GetString();
string?[] fallbacks = reader.ReadStringArray();
if (string.IsNullOrEmpty(runtime))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(runtime)));
}
runtimeFallbacks.Add(new RuntimeFallbacks(runtime, fallbacks));
}
reader.CheckEndObject();
return runtimeFallbacks;
}
private IEnumerable<Library> CreateLibraries(IEnumerable<TargetLibrary>? libraries, bool runtime, Dictionary<string, LibraryStub>? libraryStubs)
{
if (libraries == null)
{
return Enumerable.Empty<Library>();
}
return libraries
.Select(property => CreateLibrary(property, runtime, libraryStubs))
.Where(library => library != null)!;
}
private Library? CreateLibrary(TargetLibrary targetLibrary, bool runtime, Dictionary<string, LibraryStub>? libraryStubs)
{
string nameWithVersion = targetLibrary.Name;
if (libraryStubs == null || !libraryStubs.TryGetValue(nameWithVersion, out LibraryStub stub))
{
throw new InvalidOperationException(SR.Format(SR.LibraryInformationNotFound, nameWithVersion));
}
int separatorPosition = nameWithVersion.IndexOf(DependencyContextStrings.VersionSeparator);
string name = Pool(nameWithVersion.Substring(0, separatorPosition));
string version = Pool(nameWithVersion.Substring(separatorPosition + 1));
if (runtime)
{
// Runtime section of this library was trimmed by type:platform
bool? isCompilationOnly = targetLibrary.CompileOnly;
if (isCompilationOnly == true)
{
return null;
}
var runtimeAssemblyGroups = new List<RuntimeAssetGroup>();
var nativeLibraryGroups = new List<RuntimeAssetGroup>();
if (targetLibrary.RuntimeTargets != null)
{
foreach (IGrouping<string?, RuntimeTargetEntryStub> ridGroup in targetLibrary.RuntimeTargets.GroupBy(e => e.Rid))
{
RuntimeFile[] groupRuntimeAssemblies = ridGroup
.Where(e => e.Type == DependencyContextStrings.RuntimeAssetType)
.Select(e => new RuntimeFile(e.Path, e.AssemblyVersion, e.FileVersion))
.ToArray();
if (groupRuntimeAssemblies.Any())
{
runtimeAssemblyGroups.Add(new RuntimeAssetGroup(
ridGroup.Key,
groupRuntimeAssemblies.Where(a => Path.GetFileName(a.Path) != "_._")));
}
RuntimeFile[] groupNativeLibraries = ridGroup
.Where(e => e.Type == DependencyContextStrings.NativeAssetType)
.Select(e => new RuntimeFile(e.Path, e.AssemblyVersion, e.FileVersion))
.ToArray();
if (groupNativeLibraries.Any())
{
nativeLibraryGroups.Add(new RuntimeAssetGroup(
ridGroup.Key,
groupNativeLibraries.Where(a => Path.GetFileName(a.Path) != "_._")));
}
}
}
if (targetLibrary.Runtimes != null && targetLibrary.Runtimes.Count > 0)
{
runtimeAssemblyGroups.Add(new RuntimeAssetGroup(string.Empty, targetLibrary.Runtimes));
}
if (targetLibrary.Natives != null && targetLibrary.Natives.Count > 0)
{
nativeLibraryGroups.Add(new RuntimeAssetGroup(string.Empty, targetLibrary.Natives));
}
return new RuntimeLibrary(
type: stub.Type,
name: name,
version: version,
hash: stub.Hash,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: nativeLibraryGroups,
resourceAssemblies: targetLibrary.Resources ?? Enumerable.Empty<ResourceAssembly>(),
dependencies: targetLibrary.Dependencies,
serviceable: stub.Serviceable,
path: stub.Path,
hashPath: stub.HashPath,
runtimeStoreManifestName: stub.RuntimeStoreManifestName);
}
else
{
IEnumerable<string> assemblies = targetLibrary.Compilations ?? Enumerable.Empty<string>();
return new CompilationLibrary(
stub.Type,
name,
version,
stub.Hash,
assemblies,
targetLibrary.Dependencies,
stub.Serviceable,
stub.Path,
stub.HashPath);
}
}
[return: NotNullIfNotNull("s")]
private string? Pool(string? s)
{
if (s == null)
{
return null;
}
if (!_stringPool.TryGetValue(s, out string? result))
{
_stringPool[s] = s;
result = s;
}
return result;
}
private sealed class Target
{
public string Name;
public IEnumerable<TargetLibrary> Libraries;
public Target(string name, IEnumerable<TargetLibrary> libraries)
{
Name = name;
Libraries = libraries;
}
}
private struct TargetLibrary
{
public string Name;
public IEnumerable<Dependency> Dependencies;
public List<RuntimeFile>? Runtimes;
public List<RuntimeFile>? Natives;
public List<string>? Compilations;
public List<RuntimeTargetEntryStub>? RuntimeTargets;
public List<ResourceAssembly>? Resources;
public bool? CompileOnly;
}
private struct RuntimeTargetEntryStub
{
public string? Type;
public string Path;
public string? Rid;
public string? AssemblyVersion;
public string? FileVersion;
}
private struct LibraryStub
{
public string? Hash;
public string Type;
public bool Serviceable;
public string? Path;
public string? HashPath;
public string? RuntimeStoreManifestName;
}
}
}
| // 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace Microsoft.Extensions.DependencyModel
{
public class DependencyContextJsonReader : IDependencyContextReader
{
private const int UnseekableStreamInitialRentSize = 4096;
private static ReadOnlySpan<byte> Utf8Bom => new byte[] { 0xEF, 0xBB, 0xBF };
private readonly IDictionary<string, string> _stringPool = new Dictionary<string, string>();
public DependencyContext Read(Stream stream!!)
{
ArraySegment<byte> buffer = ReadToEnd(stream);
try
{
return Read(new Utf8JsonReader(buffer, isFinalBlock: true, state: default));
}
finally
{
// Holds document content, clear it before returning it.
buffer.AsSpan().Clear();
ArrayPool<byte>.Shared.Return(buffer.Array!);
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_stringPool.Clear();
}
}
public void Dispose()
{
Dispose(true);
}
// Borrowed from https://github.com/dotnet/corefx/blob/b8bc4ff80c5f7baa681e8a569d367356957ba78a/src/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs#L290-L362
private static ArraySegment<byte> ReadToEnd(Stream stream)
{
int written = 0;
byte[]? rented = null;
ReadOnlySpan<byte> utf8Bom = Utf8Bom;
try
{
if (stream.CanSeek)
{
// Ask for 1 more than the length to avoid resizing later,
// which is unnecessary in the common case where the stream length doesn't change.
long expectedLength = Math.Max(utf8Bom.Length, stream.Length - stream.Position) + 1;
rented = ArrayPool<byte>.Shared.Rent(checked((int)expectedLength));
}
else
{
rented = ArrayPool<byte>.Shared.Rent(UnseekableStreamInitialRentSize);
}
int lastRead;
// Read up to 3 bytes to see if it's the UTF-8 BOM, for parity with the behavior
// of StreamReader..ctor(Stream).
do
{
// No need for checking for growth, the minimal rent sizes both guarantee it'll fit.
Debug.Assert(rented.Length >= utf8Bom.Length);
lastRead = stream.Read(
rented,
written,
utf8Bom.Length - written);
written += lastRead;
} while (lastRead > 0 && written < utf8Bom.Length);
// If we have 3 bytes, and they're the BOM, reset the write position to 0.
if (written == utf8Bom.Length &&
utf8Bom.SequenceEqual(rented.AsSpan(0, utf8Bom.Length)))
{
written = 0;
}
do
{
if (rented.Length == written)
{
byte[] toReturn = rented;
rented = ArrayPool<byte>.Shared.Rent(checked(toReturn.Length * 2));
Buffer.BlockCopy(toReturn, 0, rented, 0, toReturn.Length);
// Holds document content, clear it.
ArrayPool<byte>.Shared.Return(toReturn, clearArray: true);
}
lastRead = stream.Read(rented, written, rented.Length - written);
written += lastRead;
} while (lastRead > 0);
return new ArraySegment<byte>(rented, 0, written);
}
catch
{
if (rented != null)
{
// Holds document content, clear it before returning it.
rented.AsSpan(0, written).Clear();
ArrayPool<byte>.Shared.Return(rented);
}
throw;
}
}
private DependencyContext Read(Utf8JsonReader reader)
{
reader.ReadStartObject();
string runtime = string.Empty;
string framework = string.Empty;
bool isPortable = true;
string? runtimeTargetName = null;
string? runtimeSignature = null;
CompilationOptions? compilationOptions = null;
List<Target>? targets = null;
Dictionary<string, LibraryStub>? libraryStubs = null;
List<RuntimeFallbacks>? runtimeFallbacks = null;
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.RuntimeTargetPropertyName:
ReadRuntimeTarget(ref reader, out runtimeTargetName, out runtimeSignature);
break;
case DependencyContextStrings.CompilationOptionsPropertName:
compilationOptions = ReadCompilationOptions(ref reader);
break;
case DependencyContextStrings.TargetsPropertyName:
targets = ReadTargets(ref reader);
break;
case DependencyContextStrings.LibrariesPropertyName:
libraryStubs = ReadLibraries(ref reader);
break;
case DependencyContextStrings.RuntimesPropertyName:
runtimeFallbacks = ReadRuntimes(ref reader);
break;
default:
reader.Skip();
break;
}
}
if (compilationOptions == null)
{
compilationOptions = CompilationOptions.Default;
}
Target? runtimeTarget = SelectRuntimeTarget(targets, runtimeTargetName);
runtimeTargetName = runtimeTarget?.Name;
if (runtimeTargetName != null)
{
int separatorIndex = runtimeTargetName.IndexOf(DependencyContextStrings.VersionSeparator);
if (separatorIndex > -1 && separatorIndex < runtimeTargetName.Length)
{
runtime = runtimeTargetName.Substring(separatorIndex + 1);
framework = runtimeTargetName.Substring(0, separatorIndex);
isPortable = false;
}
else
{
framework = runtimeTargetName;
}
}
Target? compileTarget = null;
Target? ridlessTarget = targets.FirstOrDefault(t => !IsRuntimeTarget(t.Name));
if (ridlessTarget != null)
{
compileTarget = ridlessTarget;
if (runtimeTarget == null)
{
runtimeTarget = compileTarget;
framework = ridlessTarget.Name;
}
}
if (runtimeTarget == null)
{
throw new FormatException(SR.NoRuntimeTarget);
}
return new DependencyContext(
new TargetInfo(framework, runtime, runtimeSignature, isPortable),
compilationOptions,
CreateLibraries(compileTarget?.Libraries, false, libraryStubs).Cast<CompilationLibrary>().ToArray(),
CreateLibraries(runtimeTarget.Libraries, true, libraryStubs).Cast<RuntimeLibrary>().ToArray(),
runtimeFallbacks ?? Enumerable.Empty<RuntimeFallbacks>());
}
private static Target? SelectRuntimeTarget([NotNull] List<Target>? targets, string? runtimeTargetName)
{
Target? target;
if (targets == null || targets.Count == 0)
{
throw new FormatException(SR.NoTargetsSection);
}
if (!string.IsNullOrEmpty(runtimeTargetName))
{
target = targets.FirstOrDefault(t => t.Name == runtimeTargetName);
if (target == null)
{
throw new FormatException(SR.Format(SR.TargetNotFound, runtimeTargetName));
}
}
else
{
target = targets.FirstOrDefault(t => IsRuntimeTarget(t.Name));
}
return target;
}
private static bool IsRuntimeTarget(string name)
{
return name.Contains(DependencyContextStrings.VersionSeparator);
}
private static void ReadRuntimeTarget(ref Utf8JsonReader reader, out string? runtimeTargetName, out string? runtimeSignature)
{
runtimeTargetName = null;
runtimeSignature = null;
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
switch (propertyName)
{
case DependencyContextStrings.RuntimeTargetNamePropertyName:
runtimeTargetName = propertyValue;
break;
case DependencyContextStrings.RuntimeTargetSignaturePropertyName:
runtimeSignature = propertyValue;
break;
}
}
reader.CheckEndObject();
}
private static CompilationOptions ReadCompilationOptions(ref Utf8JsonReader reader)
{
IEnumerable<string?>? defines = null;
string? languageVersion = null;
string? platform = null;
bool? allowUnsafe = null;
bool? warningsAsErrors = null;
bool? optimize = null;
string? keyFile = null;
bool? delaySign = null;
bool? publicSign = null;
string? debugType = null;
bool? emitEntryPoint = null;
bool? generateXmlDocumentation = null;
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.DefinesPropertyName:
defines = reader.ReadStringArray();
break;
case DependencyContextStrings.LanguageVersionPropertyName:
languageVersion = reader.ReadAsString();
break;
case DependencyContextStrings.PlatformPropertyName:
platform = reader.ReadAsString();
break;
case DependencyContextStrings.AllowUnsafePropertyName:
allowUnsafe = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.WarningsAsErrorsPropertyName:
warningsAsErrors = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.OptimizePropertyName:
optimize = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.KeyFilePropertyName:
keyFile = reader.ReadAsString();
break;
case DependencyContextStrings.DelaySignPropertyName:
delaySign = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.PublicSignPropertyName:
publicSign = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.DebugTypePropertyName:
debugType = reader.ReadAsString();
break;
case DependencyContextStrings.EmitEntryPointPropertyName:
emitEntryPoint = reader.ReadAsNullableBoolean();
break;
case DependencyContextStrings.GenerateXmlDocumentationPropertyName:
generateXmlDocumentation = reader.ReadAsNullableBoolean();
break;
default:
reader.Skip();
break;
}
}
reader.CheckEndObject();
return new CompilationOptions(
defines ?? Enumerable.Empty<string?>(),
languageVersion,
platform,
allowUnsafe,
warningsAsErrors,
optimize,
keyFile,
delaySign,
publicSign,
debugType,
emitEntryPoint,
generateXmlDocumentation);
}
private List<Target> ReadTargets(ref Utf8JsonReader reader)
{
reader.ReadStartObject();
var targets = new List<Target>();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? targetName = reader.GetString();
if (string.IsNullOrEmpty(targetName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(targetName)));
}
targets.Add(ReadTarget(ref reader, targetName));
}
reader.CheckEndObject();
return targets;
}
private Target ReadTarget(ref Utf8JsonReader reader, string targetName)
{
reader.ReadStartObject();
var libraries = new List<TargetLibrary>();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? targetLibraryName = reader.GetString();
if (string.IsNullOrEmpty(targetLibraryName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(targetLibraryName)));
}
libraries.Add(ReadTargetLibrary(ref reader, targetLibraryName));
}
reader.CheckEndObject();
return new Target(targetName, libraries);
}
private TargetLibrary ReadTargetLibrary(ref Utf8JsonReader reader, string targetLibraryName)
{
IEnumerable<Dependency>? dependencies = null;
List<RuntimeFile>? runtimes = null;
List<RuntimeFile>? natives = null;
List<string>? compilations = null;
List<RuntimeTargetEntryStub>? runtimeTargets = null;
List<ResourceAssembly>? resources = null;
bool? compileOnly = null;
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.DependenciesPropertyName:
dependencies = ReadTargetLibraryDependencies(ref reader);
break;
case DependencyContextStrings.RuntimeAssembliesKey:
runtimes = ReadRuntimeFiles(ref reader);
break;
case DependencyContextStrings.NativeLibrariesKey:
natives = ReadRuntimeFiles(ref reader);
break;
case DependencyContextStrings.CompileTimeAssembliesKey:
compilations = ReadPropertyNames(ref reader);
break;
case DependencyContextStrings.RuntimeTargetsPropertyName:
runtimeTargets = ReadTargetLibraryRuntimeTargets(ref reader);
break;
case DependencyContextStrings.ResourceAssembliesPropertyName:
resources = ReadTargetLibraryResources(ref reader);
break;
case DependencyContextStrings.CompilationOnlyPropertyName:
compileOnly = reader.ReadAsNullableBoolean();
break;
default:
reader.Skip();
break;
}
}
reader.CheckEndObject();
return new TargetLibrary()
{
Name = targetLibraryName,
Dependencies = dependencies ?? Enumerable.Empty<Dependency>(),
Runtimes = runtimes,
Natives = natives,
Compilations = compilations,
RuntimeTargets = runtimeTargets,
Resources = resources,
CompileOnly = compileOnly
};
}
private IEnumerable<Dependency> ReadTargetLibraryDependencies(ref Utf8JsonReader reader)
{
var dependencies = new List<Dependency>();
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? name, out string? version))
{
if (string.IsNullOrEmpty(name))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(name)));
}
if (string.IsNullOrEmpty(version))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(version)));
}
dependencies.Add(new Dependency(Pool(name), Pool(version)));
}
reader.CheckEndObject();
return dependencies;
}
private static List<string> ReadPropertyNames(ref Utf8JsonReader reader)
{
var runtimes = new List<string>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? libraryName = reader.GetString();
if (string.IsNullOrEmpty(libraryName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(libraryName)));
}
reader.Skip();
runtimes.Add(libraryName);
}
reader.CheckEndObject();
return runtimes;
}
private static List<RuntimeFile> ReadRuntimeFiles(ref Utf8JsonReader reader)
{
var runtimeFiles = new List<RuntimeFile>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? assemblyVersion = null;
string? fileVersion = null;
string? path = reader.GetString();
if (string.IsNullOrEmpty(path))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(path)));
}
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
switch (propertyName)
{
case DependencyContextStrings.AssemblyVersionPropertyName:
assemblyVersion = propertyValue;
break;
case DependencyContextStrings.FileVersionPropertyName:
fileVersion = propertyValue;
break;
}
}
reader.CheckEndObject();
runtimeFiles.Add(new RuntimeFile(path, assemblyVersion, fileVersion));
}
reader.CheckEndObject();
return runtimeFiles;
}
private List<RuntimeTargetEntryStub> ReadTargetLibraryRuntimeTargets(ref Utf8JsonReader reader)
{
var runtimeTargets = new List<RuntimeTargetEntryStub>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? runtimePath = reader.GetString();
if (string.IsNullOrEmpty(runtimePath))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(runtimePath)));
}
var runtimeTarget = new RuntimeTargetEntryStub
{
Path = runtimePath
};
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
switch (propertyName)
{
case DependencyContextStrings.RidPropertyName:
runtimeTarget.Rid = Pool(propertyValue);
break;
case DependencyContextStrings.AssetTypePropertyName:
runtimeTarget.Type = Pool(propertyValue);
break;
case DependencyContextStrings.AssemblyVersionPropertyName:
runtimeTarget.AssemblyVersion = propertyValue;
break;
case DependencyContextStrings.FileVersionPropertyName:
runtimeTarget.FileVersion = propertyValue;
break;
}
}
reader.CheckEndObject();
runtimeTargets.Add(runtimeTarget);
}
reader.CheckEndObject();
return runtimeTargets;
}
private List<ResourceAssembly> ReadTargetLibraryResources(ref Utf8JsonReader reader)
{
var resources = new List<ResourceAssembly>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? path = reader.GetString();
if (string.IsNullOrEmpty(path))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(path)));
}
string? locale = null;
reader.ReadStartObject();
while (reader.TryReadStringProperty(out string? propertyName, out string? propertyValue))
{
if (propertyName == DependencyContextStrings.LocalePropertyName)
{
locale = propertyValue;
}
}
reader.CheckEndObject();
if (locale != null)
{
resources.Add(new ResourceAssembly(path, Pool(locale)));
}
}
reader.CheckEndObject();
return resources;
}
private Dictionary<string, LibraryStub> ReadLibraries(ref Utf8JsonReader reader)
{
var libraries = new Dictionary<string, LibraryStub>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? libraryName = reader.GetString();
if (string.IsNullOrEmpty(libraryName))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(libraryName)));
}
libraries.Add(Pool(libraryName), ReadOneLibrary(ref reader));
}
reader.CheckEndObject();
return libraries;
}
private LibraryStub ReadOneLibrary(ref Utf8JsonReader reader)
{
string? hash = null;
string? type = null;
bool serviceable = false;
string? path = null;
string? hashPath = null;
string? runtimeStoreManifestName = null;
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
switch (reader.GetString())
{
case DependencyContextStrings.Sha512PropertyName:
hash = reader.ReadAsString();
break;
case DependencyContextStrings.TypePropertyName:
type = reader.ReadAsString();
break;
case DependencyContextStrings.ServiceablePropertyName:
serviceable = reader.ReadAsBoolean(defaultValue: false);
break;
case DependencyContextStrings.PathPropertyName:
path = reader.ReadAsString();
break;
case DependencyContextStrings.HashPathPropertyName:
hashPath = reader.ReadAsString();
break;
case DependencyContextStrings.RuntimeStoreManifestPropertyName:
runtimeStoreManifestName = reader.ReadAsString();
break;
default:
reader.Skip();
break;
}
}
reader.CheckEndObject();
if (string.IsNullOrEmpty(type))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(type)));
}
return new LibraryStub()
{
Hash = hash,
Type = Pool(type),
Serviceable = serviceable,
Path = path,
HashPath = hashPath,
RuntimeStoreManifestName = runtimeStoreManifestName
};
}
private static List<RuntimeFallbacks> ReadRuntimes(ref Utf8JsonReader reader)
{
var runtimeFallbacks = new List<RuntimeFallbacks>();
reader.ReadStartObject();
while (reader.Read() && reader.IsTokenTypeProperty())
{
string? runtime = reader.GetString();
string?[] fallbacks = reader.ReadStringArray();
if (string.IsNullOrEmpty(runtime))
{
throw new FormatException(SR.Format(SR.RequiredFieldNotSpecified, nameof(runtime)));
}
runtimeFallbacks.Add(new RuntimeFallbacks(runtime, fallbacks));
}
reader.CheckEndObject();
return runtimeFallbacks;
}
private IEnumerable<Library> CreateLibraries(IEnumerable<TargetLibrary>? libraries, bool runtime, Dictionary<string, LibraryStub>? libraryStubs)
{
if (libraries == null)
{
return Enumerable.Empty<Library>();
}
return libraries
.Select(property => CreateLibrary(property, runtime, libraryStubs))
.Where(library => library != null)!;
}
private Library? CreateLibrary(TargetLibrary targetLibrary, bool runtime, Dictionary<string, LibraryStub>? libraryStubs)
{
string nameWithVersion = targetLibrary.Name;
if (libraryStubs == null || !libraryStubs.TryGetValue(nameWithVersion, out LibraryStub stub))
{
throw new InvalidOperationException(SR.Format(SR.LibraryInformationNotFound, nameWithVersion));
}
int separatorPosition = nameWithVersion.IndexOf(DependencyContextStrings.VersionSeparator);
string name = Pool(nameWithVersion.Substring(0, separatorPosition));
string version = Pool(nameWithVersion.Substring(separatorPosition + 1));
if (runtime)
{
// Runtime section of this library was trimmed by type:platform
bool? isCompilationOnly = targetLibrary.CompileOnly;
if (isCompilationOnly == true)
{
return null;
}
var runtimeAssemblyGroups = new List<RuntimeAssetGroup>();
var nativeLibraryGroups = new List<RuntimeAssetGroup>();
if (targetLibrary.RuntimeTargets != null)
{
foreach (IGrouping<string?, RuntimeTargetEntryStub> ridGroup in targetLibrary.RuntimeTargets.GroupBy(e => e.Rid))
{
RuntimeFile[] groupRuntimeAssemblies = ridGroup
.Where(e => e.Type == DependencyContextStrings.RuntimeAssetType)
.Select(e => new RuntimeFile(e.Path, e.AssemblyVersion, e.FileVersion))
.ToArray();
if (groupRuntimeAssemblies.Any())
{
runtimeAssemblyGroups.Add(new RuntimeAssetGroup(
ridGroup.Key,
groupRuntimeAssemblies.Where(a => Path.GetFileName(a.Path) != "_._")));
}
RuntimeFile[] groupNativeLibraries = ridGroup
.Where(e => e.Type == DependencyContextStrings.NativeAssetType)
.Select(e => new RuntimeFile(e.Path, e.AssemblyVersion, e.FileVersion))
.ToArray();
if (groupNativeLibraries.Any())
{
nativeLibraryGroups.Add(new RuntimeAssetGroup(
ridGroup.Key,
groupNativeLibraries.Where(a => Path.GetFileName(a.Path) != "_._")));
}
}
}
if (targetLibrary.Runtimes != null && targetLibrary.Runtimes.Count > 0)
{
runtimeAssemblyGroups.Add(new RuntimeAssetGroup(string.Empty, targetLibrary.Runtimes));
}
if (targetLibrary.Natives != null && targetLibrary.Natives.Count > 0)
{
nativeLibraryGroups.Add(new RuntimeAssetGroup(string.Empty, targetLibrary.Natives));
}
return new RuntimeLibrary(
type: stub.Type,
name: name,
version: version,
hash: stub.Hash,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: nativeLibraryGroups,
resourceAssemblies: targetLibrary.Resources ?? Enumerable.Empty<ResourceAssembly>(),
dependencies: targetLibrary.Dependencies,
serviceable: stub.Serviceable,
path: stub.Path,
hashPath: stub.HashPath,
runtimeStoreManifestName: stub.RuntimeStoreManifestName);
}
else
{
IEnumerable<string> assemblies = targetLibrary.Compilations ?? Enumerable.Empty<string>();
return new CompilationLibrary(
stub.Type,
name,
version,
stub.Hash,
assemblies,
targetLibrary.Dependencies,
stub.Serviceable,
stub.Path,
stub.HashPath);
}
}
[return: NotNullIfNotNull("s")]
private string? Pool(string? s)
{
if (s == null)
{
return null;
}
if (!_stringPool.TryGetValue(s, out string? result))
{
_stringPool[s] = s;
result = s;
}
return result;
}
private sealed class Target
{
public string Name;
public IEnumerable<TargetLibrary> Libraries;
public Target(string name, IEnumerable<TargetLibrary> libraries)
{
Name = name;
Libraries = libraries;
}
}
private struct TargetLibrary
{
public string Name;
public IEnumerable<Dependency> Dependencies;
public List<RuntimeFile>? Runtimes;
public List<RuntimeFile>? Natives;
public List<string>? Compilations;
public List<RuntimeTargetEntryStub>? RuntimeTargets;
public List<ResourceAssembly>? Resources;
public bool? CompileOnly;
}
private struct RuntimeTargetEntryStub
{
public string? Type;
public string Path;
public string? Rid;
public string? AssemblyVersion;
public string? FileVersion;
}
private struct LibraryStub
{
public string? Hash;
public string Type;
public bool Serviceable;
public string? Path;
public string? HashPath;
public string? RuntimeStoreManifestName;
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/installer/tests/Assets/TestProjects/HostApiInvokerApp/HostFXR.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.Runtime.InteropServices;
namespace HostApiInvokerApp
{
public static class HostFXR
{
internal static class hostfxr
{
[Flags]
internal enum hostfxr_resolve_sdk2_flags_t : int
{
disallow_prerelease = 0x1,
}
internal enum hostfxr_resolve_sdk2_result_key_t : int
{
resolved_sdk_dir = 0,
global_json_path = 1,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct hostfxr_dotnet_environment_sdk_info
{
internal nuint size;
internal string version;
internal string path;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct hostfxr_dotnet_environment_framework_info
{
internal nuint size;
internal string name;
internal string version;
internal string path;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct hostfxr_dotnet_environment_info
{
internal nuint size;
internal string hostfxr_version;
internal string hostfxr_commit_hash;
internal nuint sdk_count;
internal IntPtr sdks;
internal nuint framework_count;
internal IntPtr frameworks;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_resolve_sdk2_result_fn(
hostfxr_resolve_sdk2_result_key_t key,
string value);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern int hostfxr_resolve_sdk2(
string exe_dir,
string working_dir,
hostfxr_resolve_sdk2_flags_t flags,
hostfxr_resolve_sdk2_result_fn result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_get_available_sdks_result_fn(
int sdk_count,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
string[] sdk_dirs);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern int hostfxr_get_available_sdks(
string exe_dir,
hostfxr_get_available_sdks_result_fn result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_error_writer_fn(
string message);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr hostfxr_set_error_writer(
hostfxr_error_writer_fn error_writer);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_get_dotnet_environment_info_result_fn(
IntPtr info,
IntPtr result_context);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern int hostfxr_get_dotnet_environment_info(
string dotnet_root,
IntPtr reserved,
hostfxr_get_dotnet_environment_info_result_fn result,
IntPtr result_context);
}
/// <summary>
/// Test invoking the native hostfxr api hostfxr_resolve_sdk2
/// </summary>
/// <param name="args[0]">hostfxr_get_available_sdks</param>
/// <param name="args[1]">Directory of dotnet executable</param>
/// <param name="args[2]">Working directory where search for global.json begins</param>
/// <param name="args[3]">Flags</param>
static void Test_hostfxr_resolve_sdk2(string[] args)
{
if (args.Length != 4)
{
throw new ArgumentException("Invalid number of arguments passed");
}
var data = new List<(hostfxr.hostfxr_resolve_sdk2_result_key_t, string)>();
int rc = hostfxr.hostfxr_resolve_sdk2(
exe_dir: args[1],
working_dir: args[2],
flags: Enum.Parse<hostfxr.hostfxr_resolve_sdk2_flags_t>(args[3]),
result: (key, value) => data.Add((key, value)));
if (rc == 0)
{
Console.WriteLine("hostfxr_resolve_sdk2:Success");
}
else
{
Console.WriteLine($"hostfxr_resolve_sdk2:Fail[{rc}]");
}
Console.WriteLine($"hostfxr_resolve_sdk2 data:[{string.Join(';', data)}]");
}
/// <summary>
/// Test invoking the native hostfxr api hostfxr_get_available_sdks
/// </summary>
/// <param name="args[0]">hostfxr_get_available_sdks</param>
/// <param name="args[1]">Directory of dotnet executable</param>
static void Test_hostfxr_get_available_sdks(string[] args)
{
if (args.Length != 2)
{
throw new ArgumentException("Invalid number of arguments passed");
}
string[] sdks = null;
int rc = hostfxr.hostfxr_get_available_sdks(
exe_dir: args[1],
(sdk_count, sdk_dirs) => sdks = sdk_dirs);
if (rc == 0)
{
Console.WriteLine("hostfxr_get_available_sdks:Success");
Console.WriteLine($"hostfxr_get_available_sdks sdks:[{string.Join(';', sdks)}]");
}
else
{
Console.WriteLine($"hostfxr_get_available_sdks:Fail[{rc}]");
}
}
static void Test_hostfxr_set_error_writer(string[] args)
{
hostfxr.hostfxr_error_writer_fn writer1 = (message) => { Console.WriteLine(nameof(writer1)); };
IntPtr writer1Ptr = Marshal.GetFunctionPointerForDelegate(writer1);
if (hostfxr.hostfxr_set_error_writer(writer1) != IntPtr.Zero)
{
throw new ApplicationException("Error writer should be null by default.");
}
hostfxr.hostfxr_error_writer_fn writer2 = (message) => { Console.WriteLine(nameof(writer2)); };
IntPtr writer2Ptr = Marshal.GetFunctionPointerForDelegate(writer2);
IntPtr previousWriterPtr = hostfxr.hostfxr_set_error_writer(writer2);
if (previousWriterPtr != writer1Ptr)
{
throw new ApplicationException("First: The previous writer returned is not the one expected.");
}
previousWriterPtr = hostfxr.hostfxr_set_error_writer(null);
if (previousWriterPtr != writer2Ptr)
{
throw new ApplicationException("Second: The previous writer returned is not the one expected.");
}
}
/// <summary>
/// Test that invokes native api hostfxr_get_dotnet_environment_info.
/// </summary>
/// <param name="args[0]">hostfxr_get_dotnet_environment_info</param>
/// <param name="args[1]">(Optional) Path to the directory with dotnet.exe</param>
static void Test_hostfxr_get_dotnet_environment_info(string[] args)
{
string dotnetExeDir = null;
if (args.Length >= 2)
dotnetExeDir = args[1];
string hostfxr_version;
string hostfxr_commit_hash;
List<hostfxr.hostfxr_dotnet_environment_sdk_info> sdks = new List<hostfxr.hostfxr_dotnet_environment_sdk_info>();
List<hostfxr.hostfxr_dotnet_environment_framework_info> frameworks = new List<hostfxr.hostfxr_dotnet_environment_framework_info>();
hostfxr.hostfxr_get_dotnet_environment_info_result_fn result_fn = (IntPtr info, IntPtr result_context) =>
{
hostfxr.hostfxr_dotnet_environment_info environment_info = Marshal.PtrToStructure<hostfxr.hostfxr_dotnet_environment_info>(info);
hostfxr_version = environment_info.hostfxr_version;
hostfxr_commit_hash = environment_info.hostfxr_commit_hash;
int env_info_size = Marshal.SizeOf(environment_info);
if ((nuint)env_info_size != environment_info.size)
throw new Exception($"Size field value of hostfxr_dotnet_environment_info struct is {environment_info.size} but {env_info_size} was expected.");
for (int i = 0; i < (int)environment_info.sdk_count; i++)
{
IntPtr pSdkInfo = new IntPtr(environment_info.sdks.ToInt64() + (i * Marshal.SizeOf<hostfxr.hostfxr_dotnet_environment_sdk_info>()));
sdks.Add(Marshal.PtrToStructure<hostfxr.hostfxr_dotnet_environment_sdk_info>(pSdkInfo));
if ((nuint)Marshal.SizeOf(sdks[i]) != sdks[i].size)
throw new Exception($"Size field value of hostfxr_dotnet_environment_sdk_info struct is {sdks[i].size} but {Marshal.SizeOf(sdks[i])} was expected.");
}
for (int i = 0; i < (int)environment_info.framework_count; i++)
{
IntPtr pFrameworkInfo = new IntPtr(environment_info.frameworks.ToInt64() + (i * Marshal.SizeOf<hostfxr.hostfxr_dotnet_environment_framework_info>()));
frameworks.Add(Marshal.PtrToStructure<hostfxr.hostfxr_dotnet_environment_framework_info>(pFrameworkInfo));
if ((nuint)Marshal.SizeOf(frameworks[i]) != frameworks[i].size)
throw new Exception($"Size field value of hostfxr_dotnet_environment_framework_info struct is {frameworks[i].size} but {Marshal.SizeOf(frameworks[i])} was expected.");
}
long result_context_as_int = result_context.ToInt64();
if (result_context_as_int != 42)
throw new Exception($"Invalid result_context value: expected 42 but was {result_context_as_int}.");
};
if (dotnetExeDir == "test_invalid_result_ptr")
result_fn = null;
IntPtr reserved_ptr = IntPtr.Zero;
if (dotnetExeDir == "test_invalid_reserved_ptr")
reserved_ptr = new IntPtr(11);
int rc = hostfxr.hostfxr_get_dotnet_environment_info(
dotnet_root: dotnetExeDir,
reserved: reserved_ptr,
result: result_fn,
result_context: new IntPtr(42));
if (rc != 0)
{
Console.WriteLine($"hostfxr_get_dotnet_environment_info:Fail[{rc}]");
}
Console.WriteLine($"hostfxr_get_dotnet_environment_info sdk versions:[{string.Join(";", sdks.Select(s => s.version).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info sdk paths:[{string.Join(";", sdks.Select(s => s.path).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info framework names:[{string.Join(";", frameworks.Select(f => f.name).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info framework versions:[{string.Join(";", frameworks.Select(f => f.version).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info framework paths:[{string.Join(";", frameworks.Select(f => f.path).ToList())}]");
Console.WriteLine("hostfxr_get_dotnet_environment_info:Success");
}
public static bool RunTest(string apiToTest, string[] args)
{
switch (apiToTest)
{
case nameof(hostfxr.hostfxr_resolve_sdk2):
Test_hostfxr_resolve_sdk2(args);
break;
case nameof(hostfxr.hostfxr_get_available_sdks):
Test_hostfxr_get_available_sdks(args);
break;
case nameof(Test_hostfxr_set_error_writer):
Test_hostfxr_set_error_writer(args);
break;
case nameof(hostfxr.hostfxr_get_dotnet_environment_info):
Test_hostfxr_get_dotnet_environment_info(args);
break;
default:
return false;
}
Utils.LogModulePath("hostfxr");
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;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace HostApiInvokerApp
{
public static class HostFXR
{
internal static class hostfxr
{
[Flags]
internal enum hostfxr_resolve_sdk2_flags_t : int
{
disallow_prerelease = 0x1,
}
internal enum hostfxr_resolve_sdk2_result_key_t : int
{
resolved_sdk_dir = 0,
global_json_path = 1,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct hostfxr_dotnet_environment_sdk_info
{
internal nuint size;
internal string version;
internal string path;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct hostfxr_dotnet_environment_framework_info
{
internal nuint size;
internal string name;
internal string version;
internal string path;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct hostfxr_dotnet_environment_info
{
internal nuint size;
internal string hostfxr_version;
internal string hostfxr_commit_hash;
internal nuint sdk_count;
internal IntPtr sdks;
internal nuint framework_count;
internal IntPtr frameworks;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_resolve_sdk2_result_fn(
hostfxr_resolve_sdk2_result_key_t key,
string value);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern int hostfxr_resolve_sdk2(
string exe_dir,
string working_dir,
hostfxr_resolve_sdk2_flags_t flags,
hostfxr_resolve_sdk2_result_fn result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_get_available_sdks_result_fn(
int sdk_count,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
string[] sdk_dirs);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern int hostfxr_get_available_sdks(
string exe_dir,
hostfxr_get_available_sdks_result_fn result);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_error_writer_fn(
string message);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr hostfxr_set_error_writer(
hostfxr_error_writer_fn error_writer);
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
internal delegate void hostfxr_get_dotnet_environment_info_result_fn(
IntPtr info,
IntPtr result_context);
[DllImport(nameof(hostfxr), CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern int hostfxr_get_dotnet_environment_info(
string dotnet_root,
IntPtr reserved,
hostfxr_get_dotnet_environment_info_result_fn result,
IntPtr result_context);
}
/// <summary>
/// Test invoking the native hostfxr api hostfxr_resolve_sdk2
/// </summary>
/// <param name="args[0]">hostfxr_get_available_sdks</param>
/// <param name="args[1]">Directory of dotnet executable</param>
/// <param name="args[2]">Working directory where search for global.json begins</param>
/// <param name="args[3]">Flags</param>
static void Test_hostfxr_resolve_sdk2(string[] args)
{
if (args.Length != 4)
{
throw new ArgumentException("Invalid number of arguments passed");
}
var data = new List<(hostfxr.hostfxr_resolve_sdk2_result_key_t, string)>();
int rc = hostfxr.hostfxr_resolve_sdk2(
exe_dir: args[1],
working_dir: args[2],
flags: Enum.Parse<hostfxr.hostfxr_resolve_sdk2_flags_t>(args[3]),
result: (key, value) => data.Add((key, value)));
if (rc == 0)
{
Console.WriteLine("hostfxr_resolve_sdk2:Success");
}
else
{
Console.WriteLine($"hostfxr_resolve_sdk2:Fail[{rc}]");
}
Console.WriteLine($"hostfxr_resolve_sdk2 data:[{string.Join(';', data)}]");
}
/// <summary>
/// Test invoking the native hostfxr api hostfxr_get_available_sdks
/// </summary>
/// <param name="args[0]">hostfxr_get_available_sdks</param>
/// <param name="args[1]">Directory of dotnet executable</param>
static void Test_hostfxr_get_available_sdks(string[] args)
{
if (args.Length != 2)
{
throw new ArgumentException("Invalid number of arguments passed");
}
string[] sdks = null;
int rc = hostfxr.hostfxr_get_available_sdks(
exe_dir: args[1],
(sdk_count, sdk_dirs) => sdks = sdk_dirs);
if (rc == 0)
{
Console.WriteLine("hostfxr_get_available_sdks:Success");
Console.WriteLine($"hostfxr_get_available_sdks sdks:[{string.Join(';', sdks)}]");
}
else
{
Console.WriteLine($"hostfxr_get_available_sdks:Fail[{rc}]");
}
}
static void Test_hostfxr_set_error_writer(string[] args)
{
hostfxr.hostfxr_error_writer_fn writer1 = (message) => { Console.WriteLine(nameof(writer1)); };
IntPtr writer1Ptr = Marshal.GetFunctionPointerForDelegate(writer1);
if (hostfxr.hostfxr_set_error_writer(writer1) != IntPtr.Zero)
{
throw new ApplicationException("Error writer should be null by default.");
}
hostfxr.hostfxr_error_writer_fn writer2 = (message) => { Console.WriteLine(nameof(writer2)); };
IntPtr writer2Ptr = Marshal.GetFunctionPointerForDelegate(writer2);
IntPtr previousWriterPtr = hostfxr.hostfxr_set_error_writer(writer2);
if (previousWriterPtr != writer1Ptr)
{
throw new ApplicationException("First: The previous writer returned is not the one expected.");
}
previousWriterPtr = hostfxr.hostfxr_set_error_writer(null);
if (previousWriterPtr != writer2Ptr)
{
throw new ApplicationException("Second: The previous writer returned is not the one expected.");
}
}
/// <summary>
/// Test that invokes native api hostfxr_get_dotnet_environment_info.
/// </summary>
/// <param name="args[0]">hostfxr_get_dotnet_environment_info</param>
/// <param name="args[1]">(Optional) Path to the directory with dotnet.exe</param>
static void Test_hostfxr_get_dotnet_environment_info(string[] args)
{
string dotnetExeDir = null;
if (args.Length >= 2)
dotnetExeDir = args[1];
string hostfxr_version;
string hostfxr_commit_hash;
List<hostfxr.hostfxr_dotnet_environment_sdk_info> sdks = new List<hostfxr.hostfxr_dotnet_environment_sdk_info>();
List<hostfxr.hostfxr_dotnet_environment_framework_info> frameworks = new List<hostfxr.hostfxr_dotnet_environment_framework_info>();
hostfxr.hostfxr_get_dotnet_environment_info_result_fn result_fn = (IntPtr info, IntPtr result_context) =>
{
hostfxr.hostfxr_dotnet_environment_info environment_info = Marshal.PtrToStructure<hostfxr.hostfxr_dotnet_environment_info>(info);
hostfxr_version = environment_info.hostfxr_version;
hostfxr_commit_hash = environment_info.hostfxr_commit_hash;
int env_info_size = Marshal.SizeOf(environment_info);
if ((nuint)env_info_size != environment_info.size)
throw new Exception($"Size field value of hostfxr_dotnet_environment_info struct is {environment_info.size} but {env_info_size} was expected.");
for (int i = 0; i < (int)environment_info.sdk_count; i++)
{
IntPtr pSdkInfo = new IntPtr(environment_info.sdks.ToInt64() + (i * Marshal.SizeOf<hostfxr.hostfxr_dotnet_environment_sdk_info>()));
sdks.Add(Marshal.PtrToStructure<hostfxr.hostfxr_dotnet_environment_sdk_info>(pSdkInfo));
if ((nuint)Marshal.SizeOf(sdks[i]) != sdks[i].size)
throw new Exception($"Size field value of hostfxr_dotnet_environment_sdk_info struct is {sdks[i].size} but {Marshal.SizeOf(sdks[i])} was expected.");
}
for (int i = 0; i < (int)environment_info.framework_count; i++)
{
IntPtr pFrameworkInfo = new IntPtr(environment_info.frameworks.ToInt64() + (i * Marshal.SizeOf<hostfxr.hostfxr_dotnet_environment_framework_info>()));
frameworks.Add(Marshal.PtrToStructure<hostfxr.hostfxr_dotnet_environment_framework_info>(pFrameworkInfo));
if ((nuint)Marshal.SizeOf(frameworks[i]) != frameworks[i].size)
throw new Exception($"Size field value of hostfxr_dotnet_environment_framework_info struct is {frameworks[i].size} but {Marshal.SizeOf(frameworks[i])} was expected.");
}
long result_context_as_int = result_context.ToInt64();
if (result_context_as_int != 42)
throw new Exception($"Invalid result_context value: expected 42 but was {result_context_as_int}.");
};
if (dotnetExeDir == "test_invalid_result_ptr")
result_fn = null;
IntPtr reserved_ptr = IntPtr.Zero;
if (dotnetExeDir == "test_invalid_reserved_ptr")
reserved_ptr = new IntPtr(11);
int rc = hostfxr.hostfxr_get_dotnet_environment_info(
dotnet_root: dotnetExeDir,
reserved: reserved_ptr,
result: result_fn,
result_context: new IntPtr(42));
if (rc != 0)
{
Console.WriteLine($"hostfxr_get_dotnet_environment_info:Fail[{rc}]");
}
Console.WriteLine($"hostfxr_get_dotnet_environment_info sdk versions:[{string.Join(";", sdks.Select(s => s.version).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info sdk paths:[{string.Join(";", sdks.Select(s => s.path).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info framework names:[{string.Join(";", frameworks.Select(f => f.name).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info framework versions:[{string.Join(";", frameworks.Select(f => f.version).ToList())}]");
Console.WriteLine($"hostfxr_get_dotnet_environment_info framework paths:[{string.Join(";", frameworks.Select(f => f.path).ToList())}]");
Console.WriteLine("hostfxr_get_dotnet_environment_info:Success");
}
public static bool RunTest(string apiToTest, string[] args)
{
switch (apiToTest)
{
case nameof(hostfxr.hostfxr_resolve_sdk2):
Test_hostfxr_resolve_sdk2(args);
break;
case nameof(hostfxr.hostfxr_get_available_sdks):
Test_hostfxr_get_available_sdks(args);
break;
case nameof(Test_hostfxr_set_error_writer):
Test_hostfxr_set_error_writer(args);
break;
case nameof(hostfxr.hostfxr_get_dotnet_environment_info):
Test_hostfxr_get_dotnet_environment_info(args);
break;
default:
return false;
}
Utils.LogModulePath("hostfxr");
return true;
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightLogicalNarrowingSaturateLower.Vector64.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 ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_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__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray, UInt16[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<UInt32, 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<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1 testClass)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1 testClass)
{
fixed (Vector128<UInt32>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly byte Imm = 1;
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data, new UInt16[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.ShiftRightLogicalNarrowingSaturateLower(
Unsafe.Read<Vector128<UInt32>>(_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.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(_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.ShiftRightLogicalNarrowingSaturateLower), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogicalNarrowingSaturateLower), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar = &_clsVar)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>(_dataTable.inArrayPtr);
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(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((UInt32*)(_dataTable.inArrayPtr));
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1();
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(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__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1();
fixed (Vector128<UInt32>* pFld = &test._fld)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(pFld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(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.ShiftRightLogicalNarrowingSaturateLower(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.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(&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<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ShiftRightLogicalNarrowingSaturate(firstOp[i], Imm) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogicalNarrowingSaturateLower)}<UInt16>(Vector128<UInt32>, 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 ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_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__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray, UInt16[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<UInt32, 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<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1 testClass)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1 testClass)
{
fixed (Vector128<UInt32>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly byte Imm = 1;
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data, new UInt16[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.ShiftRightLogicalNarrowingSaturateLower(
Unsafe.Read<Vector128<UInt32>>(_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.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(_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.ShiftRightLogicalNarrowingSaturateLower), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogicalNarrowingSaturateLower), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar = &_clsVar)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>(_dataTable.inArrayPtr);
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(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((UInt32*)(_dataTable.inArrayPtr));
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1();
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(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__ShiftRightLogicalNarrowingSaturateLower_Vector64_UInt16_1();
fixed (Vector128<UInt32>* pFld = &test._fld)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(pFld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(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.ShiftRightLogicalNarrowingSaturateLower(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.ShiftRightLogicalNarrowingSaturateLower(
AdvSimd.LoadVector128((UInt32*)(&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<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ShiftRightLogicalNarrowingSaturate(firstOp[i], Imm) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogicalNarrowingSaturateLower)}<UInt16>(Vector128<UInt32>, 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,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Runtime/tests/System/Reflection/AssemblyKeyNameAttributeTests.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.Reflection.Tests
{
public class AssemblyKeyNameAttributeTests
{
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("keyName")]
public void Ctor_String(string keyName)
{
var attribute = new AssemblyKeyNameAttribute(keyName);
Assert.Equal(keyName, attribute.KeyName);
}
}
}
| // 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.Reflection.Tests
{
public class AssemblyKeyNameAttributeTests
{
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("keyName")]
public void Ctor_String(string keyName)
{
var attribute = new AssemblyKeyNameAttribute(keyName);
Assert.Equal(keyName, attribute.KeyName);
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Data.Common/src/System/Data/IDataParameterCollection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
namespace System.Data
{
public interface IDataParameterCollection : IList
{
object this[string parameterName] { get; set; }
bool Contains(string parameterName);
int IndexOf(string parameterName);
void RemoveAt(string parameterName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
namespace System.Data
{
public interface IDataParameterCollection : IList
{
object this[string parameterName] { get; set; }
bool Contains(string parameterName);
int IndexOf(string parameterName);
void RemoveAt(string parameterName);
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesigntimeLicenseContextSerializerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.IO;
using System.Reflection;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.ComponentModel.Design.Tests
{
public static class DesigntimeLicenseContextSerializerTests
{
private const string enableBinaryFormatterInTypeConverter = "System.ComponentModel.TypeConverter.EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization";
private const string enableBinaryFormatter = "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization";
public static bool AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform => PlatformDetection.IsBinaryFormatterSupported && RemoteExecutor.IsSupported;
private static void VerifyStreamFormatting(Stream stream)
{
AppContext.TryGetSwitch(enableBinaryFormatterInTypeConverter, out bool binaryFormatterUsageInTypeConverterIsEnabled);
long position = stream.Position;
int firstByte = stream.ReadByte();
if (binaryFormatterUsageInTypeConverterIsEnabled)
{
Assert.Equal(0, firstByte);
}
else
{
Assert.Equal(255, firstByte);
}
stream.Seek(position, SeekOrigin.Begin);
}
[ConditionalTheory(nameof(AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform))]
[InlineData(false, "key")]
[InlineData(true, "key")]
[InlineData(false, "")]
[InlineData(true, "")]
public static void SerializeAndDeserialize(bool useBinaryFormatter, string key)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
if (useBinaryFormatter)
{
options.RuntimeConfigurationOptions.Add(enableBinaryFormatterInTypeConverter, bool.TrueString);
}
RemoteExecutor.Invoke((key) =>
{
var context = new DesigntimeLicenseContext();
context.SetSavedLicenseKey(typeof(int), key);
var assembly = typeof(DesigntimeLicenseContextSerializer).Assembly;
Type runtimeLicenseContextType = assembly.GetType("System.ComponentModel.Design.RuntimeLicenseContext");
Assert.NotNull(runtimeLicenseContextType);
object runtimeLicenseContext = Activator.CreateInstance(runtimeLicenseContextType);
FieldInfo _savedLicenseKeys = runtimeLicenseContextType.GetField("_savedLicenseKeys", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(_savedLicenseKeys);
_savedLicenseKeys.SetValue(runtimeLicenseContext, new Hashtable());
Assert.NotNull(runtimeLicenseContext);
Type designtimeLicenseContextSerializer = assembly.GetType("System.ComponentModel.Design.DesigntimeLicenseContextSerializer");
Assert.NotNull(designtimeLicenseContextSerializer);
MethodInfo deserializeMethod = designtimeLicenseContextSerializer.GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);
using (MemoryStream stream = new MemoryStream())
{
long position = stream.Position;
DesigntimeLicenseContextSerializer.Serialize(stream, key, context);
stream.Seek(position, SeekOrigin.Begin);
VerifyStreamFormatting(stream);
deserializeMethod.Invoke(null, new object[] { stream, key, runtimeLicenseContext });
Hashtable savedLicenseKeys = runtimeLicenseContext.GetType().GetField("_savedLicenseKeys", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(runtimeLicenseContext) as Hashtable;
Assert.NotNull(savedLicenseKeys);
var value = savedLicenseKeys[typeof(int).AssemblyQualifiedName];
Assert.True(value is string);
Assert.Equal(key, value);
}
}, key, options).Dispose();
}
[ConditionalTheory(nameof(AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform))]
[InlineData("key")]
[InlineData("")]
public static void SerializeWithBinaryFormatter_DeserializeWithBinaryWriter(string key)
{
AppContext.SetSwitch(enableBinaryFormatter, true);
AppContext.SetSwitch(enableBinaryFormatterInTypeConverter, true);
var context = new DesigntimeLicenseContext();
context.SetSavedLicenseKey(typeof(int), key);
string tempPath = Path.GetTempPath();
try
{
using (MemoryStream stream = new MemoryStream())
{
long position = stream.Position;
DesigntimeLicenseContextSerializer.Serialize(stream, key, context);
stream.Seek(position, SeekOrigin.Begin);
VerifyStreamFormatting(stream);
using (FileStream outStream = File.Create(Path.Combine(tempPath, "_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter")))
{
stream.Seek(position, SeekOrigin.Begin);
stream.CopyTo(outStream);
}
}
RemoteInvokeHandle handle = RemoteExecutor.Invoke((key) =>
{
var assembly = typeof(DesigntimeLicenseContextSerializer).Assembly;
Type runtimeLicenseContextType = assembly.GetType("System.ComponentModel.Design.RuntimeLicenseContext");
Assert.NotNull(runtimeLicenseContextType);
object runtimeLicenseContext = Activator.CreateInstance(runtimeLicenseContextType);
Assert.NotNull(runtimeLicenseContext);
FieldInfo _savedLicenseKeys = runtimeLicenseContextType.GetField("_savedLicenseKeys", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(_savedLicenseKeys);
_savedLicenseKeys.SetValue(runtimeLicenseContext, new Hashtable());
Type designtimeLicenseContextSerializer = assembly.GetType("System.ComponentModel.Design.DesigntimeLicenseContextSerializer");
Assert.NotNull(designtimeLicenseContextSerializer);
MethodInfo deserializeMethod = designtimeLicenseContextSerializer.GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(deserializeMethod);
string tempPath = Path.GetTempPath();
using (FileStream stream = File.Open(Path.Combine(tempPath, "_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter"), FileMode.Open))
{
TargetInvocationException exception = Assert.Throws<TargetInvocationException>(() => deserializeMethod.Invoke(null, new object[] { stream, key, runtimeLicenseContext }));
Assert.IsType<NotSupportedException>(exception.InnerException);
}
}, key);
handle.Process.WaitForExit();
handle.Dispose();
}
finally
{
File.Delete(Path.Combine(tempPath, "_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter"));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.IO;
using System.Reflection;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.ComponentModel.Design.Tests
{
public static class DesigntimeLicenseContextSerializerTests
{
private const string enableBinaryFormatterInTypeConverter = "System.ComponentModel.TypeConverter.EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization";
private const string enableBinaryFormatter = "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization";
public static bool AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform => PlatformDetection.IsBinaryFormatterSupported && RemoteExecutor.IsSupported;
private static void VerifyStreamFormatting(Stream stream)
{
AppContext.TryGetSwitch(enableBinaryFormatterInTypeConverter, out bool binaryFormatterUsageInTypeConverterIsEnabled);
long position = stream.Position;
int firstByte = stream.ReadByte();
if (binaryFormatterUsageInTypeConverterIsEnabled)
{
Assert.Equal(0, firstByte);
}
else
{
Assert.Equal(255, firstByte);
}
stream.Seek(position, SeekOrigin.Begin);
}
[ConditionalTheory(nameof(AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform))]
[InlineData(false, "key")]
[InlineData(true, "key")]
[InlineData(false, "")]
[InlineData(true, "")]
public static void SerializeAndDeserialize(bool useBinaryFormatter, string key)
{
RemoteInvokeOptions options = new RemoteInvokeOptions();
if (useBinaryFormatter)
{
options.RuntimeConfigurationOptions.Add(enableBinaryFormatterInTypeConverter, bool.TrueString);
}
RemoteExecutor.Invoke((key) =>
{
var context = new DesigntimeLicenseContext();
context.SetSavedLicenseKey(typeof(int), key);
var assembly = typeof(DesigntimeLicenseContextSerializer).Assembly;
Type runtimeLicenseContextType = assembly.GetType("System.ComponentModel.Design.RuntimeLicenseContext");
Assert.NotNull(runtimeLicenseContextType);
object runtimeLicenseContext = Activator.CreateInstance(runtimeLicenseContextType);
FieldInfo _savedLicenseKeys = runtimeLicenseContextType.GetField("_savedLicenseKeys", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(_savedLicenseKeys);
_savedLicenseKeys.SetValue(runtimeLicenseContext, new Hashtable());
Assert.NotNull(runtimeLicenseContext);
Type designtimeLicenseContextSerializer = assembly.GetType("System.ComponentModel.Design.DesigntimeLicenseContextSerializer");
Assert.NotNull(designtimeLicenseContextSerializer);
MethodInfo deserializeMethod = designtimeLicenseContextSerializer.GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);
using (MemoryStream stream = new MemoryStream())
{
long position = stream.Position;
DesigntimeLicenseContextSerializer.Serialize(stream, key, context);
stream.Seek(position, SeekOrigin.Begin);
VerifyStreamFormatting(stream);
deserializeMethod.Invoke(null, new object[] { stream, key, runtimeLicenseContext });
Hashtable savedLicenseKeys = runtimeLicenseContext.GetType().GetField("_savedLicenseKeys", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(runtimeLicenseContext) as Hashtable;
Assert.NotNull(savedLicenseKeys);
var value = savedLicenseKeys[typeof(int).AssemblyQualifiedName];
Assert.True(value is string);
Assert.Equal(key, value);
}
}, key, options).Dispose();
}
[ConditionalTheory(nameof(AreBinaryFormatterAndRemoteExecutorSupportedOnThisPlatform))]
[InlineData("key")]
[InlineData("")]
public static void SerializeWithBinaryFormatter_DeserializeWithBinaryWriter(string key)
{
AppContext.SetSwitch(enableBinaryFormatter, true);
AppContext.SetSwitch(enableBinaryFormatterInTypeConverter, true);
var context = new DesigntimeLicenseContext();
context.SetSavedLicenseKey(typeof(int), key);
string tempPath = Path.GetTempPath();
try
{
using (MemoryStream stream = new MemoryStream())
{
long position = stream.Position;
DesigntimeLicenseContextSerializer.Serialize(stream, key, context);
stream.Seek(position, SeekOrigin.Begin);
VerifyStreamFormatting(stream);
using (FileStream outStream = File.Create(Path.Combine(tempPath, "_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter")))
{
stream.Seek(position, SeekOrigin.Begin);
stream.CopyTo(outStream);
}
}
RemoteInvokeHandle handle = RemoteExecutor.Invoke((key) =>
{
var assembly = typeof(DesigntimeLicenseContextSerializer).Assembly;
Type runtimeLicenseContextType = assembly.GetType("System.ComponentModel.Design.RuntimeLicenseContext");
Assert.NotNull(runtimeLicenseContextType);
object runtimeLicenseContext = Activator.CreateInstance(runtimeLicenseContextType);
Assert.NotNull(runtimeLicenseContext);
FieldInfo _savedLicenseKeys = runtimeLicenseContextType.GetField("_savedLicenseKeys", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(_savedLicenseKeys);
_savedLicenseKeys.SetValue(runtimeLicenseContext, new Hashtable());
Type designtimeLicenseContextSerializer = assembly.GetType("System.ComponentModel.Design.DesigntimeLicenseContextSerializer");
Assert.NotNull(designtimeLicenseContextSerializer);
MethodInfo deserializeMethod = designtimeLicenseContextSerializer.GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(deserializeMethod);
string tempPath = Path.GetTempPath();
using (FileStream stream = File.Open(Path.Combine(tempPath, "_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter"), FileMode.Open))
{
TargetInvocationException exception = Assert.Throws<TargetInvocationException>(() => deserializeMethod.Invoke(null, new object[] { stream, key, runtimeLicenseContext }));
Assert.IsType<NotSupportedException>(exception.InnerException);
}
}, key);
handle.Process.WaitForExit();
handle.Dispose();
}
finally
{
File.Delete(Path.Combine(tempPath, "_temp_SerializeWithBinaryFormatter_DeserializeWithBinaryWriter"));
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.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.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.ComponentModel;
using System.Collections.Generic;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlAttributeOverrides
{
private readonly Dictionary<Type, Dictionary<string, XmlAttributes?>> _types = new Dictionary<Type, Dictionary<string, XmlAttributes?>>();
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Add(Type type, XmlAttributes attributes)
{
Add(type, string.Empty, attributes);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Add(Type type, string member, XmlAttributes? attributes)
{
Dictionary<string, XmlAttributes?>? members;
if (!_types.TryGetValue(type, out members))
{
members = new Dictionary<string, XmlAttributes?>();
_types.Add(type, members);
}
else if (members.ContainsKey(member))
{
throw new InvalidOperationException(SR.Format(SR.XmlAttributeSetAgain, type.FullName, member));
}
members.Add(member, attributes);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlAttributes? this[Type type]
{
get
{
return this[type, string.Empty];
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlAttributes? this[Type type, string member]
{
get
{
Dictionary<string, XmlAttributes?>? members;
XmlAttributes? attributes;
return _types.TryGetValue(type, out members) && members.TryGetValue(member, out attributes)
? attributes
: null;
}
}
}
}
| // 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.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.ComponentModel;
using System.Collections.Generic;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlAttributeOverrides
{
private readonly Dictionary<Type, Dictionary<string, XmlAttributes?>> _types = new Dictionary<Type, Dictionary<string, XmlAttributes?>>();
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Add(Type type, XmlAttributes attributes)
{
Add(type, string.Empty, attributes);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Add(Type type, string member, XmlAttributes? attributes)
{
Dictionary<string, XmlAttributes?>? members;
if (!_types.TryGetValue(type, out members))
{
members = new Dictionary<string, XmlAttributes?>();
_types.Add(type, members);
}
else if (members.ContainsKey(member))
{
throw new InvalidOperationException(SR.Format(SR.XmlAttributeSetAgain, type.FullName, member));
}
members.Add(member, attributes);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlAttributes? this[Type type]
{
get
{
return this[type, string.Empty];
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlAttributes? this[Type type, string member]
{
get
{
Dictionary<string, XmlAttributes?>? members;
XmlAttributes? attributes;
return _types.TryGetValue(type, out members) && members.TryGetValue(member, out attributes)
? attributes
: null;
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGeneratorOptions.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.CodeAnalysis.Diagnostics;
namespace Microsoft.Interop
{
internal record LibraryImportGeneratorOptions(bool GenerateForwarders, bool UseMarshalType)
{
public LibraryImportGeneratorOptions(AnalyzerConfigOptions options)
: this(options.GenerateForwarders(), options.UseMarshalType())
{
}
}
public static class OptionsHelper
{
public const string UseMarshalTypeOption = "build_property.LibraryImportGenerator_UseMarshalType";
public const string GenerateForwardersOption = "build_property.LibraryImportGenerator_GenerateForwarders";
private static bool GetBoolOption(this AnalyzerConfigOptions options, string key)
{
return options.TryGetValue(key, out string? value)
&& bool.TryParse(value, out bool result)
&& result;
}
internal static bool UseMarshalType(this AnalyzerConfigOptions options) => options.GetBoolOption(UseMarshalTypeOption);
internal static bool GenerateForwarders(this AnalyzerConfigOptions options) => options.GetBoolOption(GenerateForwardersOption);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.Interop
{
internal record LibraryImportGeneratorOptions(bool GenerateForwarders, bool UseMarshalType)
{
public LibraryImportGeneratorOptions(AnalyzerConfigOptions options)
: this(options.GenerateForwarders(), options.UseMarshalType())
{
}
}
public static class OptionsHelper
{
public const string UseMarshalTypeOption = "build_property.LibraryImportGenerator_UseMarshalType";
public const string GenerateForwardersOption = "build_property.LibraryImportGenerator_GenerateForwarders";
private static bool GetBoolOption(this AnalyzerConfigOptions options, string key)
{
return options.TryGetValue(key, out string? value)
&& bool.TryParse(value, out bool result)
&& result;
}
internal static bool UseMarshalType(this AnalyzerConfigOptions options) => options.GetBoolOption(UseMarshalTypeOption);
internal static bool GenerateForwarders(this AnalyzerConfigOptions options) => options.GetBoolOption(GenerateForwardersOption);
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/General/Vector64/Subtract.SByte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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 SubtractSByte()
{
var test = new VectorBinaryOpTest__SubtractSByte();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__SubtractSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<SByte> _fld1;
public Vector64<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__SubtractSByte testClass)
{
var result = Vector64.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector64<SByte> _clsVar1;
private static Vector64<SByte> _clsVar2;
private Vector64<SByte> _fld1;
private Vector64<SByte> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__SubtractSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public VectorBinaryOpTest__SubtractSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Subtract(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), new Type[] {
typeof(Vector64<SByte>),
typeof(Vector64<SByte>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(SByte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr);
var result = Vector64.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__SubtractSByte();
var result = Vector64.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<SByte> op1, Vector64<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (sbyte)(left[0] - right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (sbyte)(left[i] - right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Subtract)}<SByte>(Vector64<SByte>, Vector64<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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 SubtractSByte()
{
var test = new VectorBinaryOpTest__SubtractSByte();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__SubtractSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<SByte> _fld1;
public Vector64<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__SubtractSByte testClass)
{
var result = Vector64.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector64<SByte> _clsVar1;
private static Vector64<SByte> _clsVar2;
private Vector64<SByte> _fld1;
private Vector64<SByte> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__SubtractSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public VectorBinaryOpTest__SubtractSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Subtract(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), new Type[] {
typeof(Vector64<SByte>),
typeof(Vector64<SByte>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Subtract), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(SByte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr);
var result = Vector64.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__SubtractSByte();
var result = Vector64.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<SByte> op1, Vector64<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (sbyte)(left[0] - right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (sbyte)(left[i] - right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Subtract)}<SByte>(Vector64<SByte>, Vector64<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Data.Common/src/System/Data/IDataParameter.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.CodeAnalysis;
namespace System.Data
{
public interface IDataParameter
{
DbType DbType { get; set; }
ParameterDirection Direction { get; set; }
bool IsNullable { get; }
[AllowNull]
string ParameterName { get; set; }
[AllowNull]
string SourceColumn { get; set; }
DataRowVersion SourceVersion { get; set; }
object? Value { 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.Diagnostics.CodeAnalysis;
namespace System.Data
{
public interface IDataParameter
{
DbType DbType { get; set; }
ParameterDirection Direction { get; set; }
bool IsNullable { get; }
[AllowNull]
string ParameterName { get; set; }
[AllowNull]
string SourceColumn { get; set; }
DataRowVersion SourceVersion { get; set; }
object? Value { get; set; }
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Options/OrderingQueryOperator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderingQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Represents operators AsOrdered and AsUnordered. In the current implementation, it
/// simply turns on preservation globally in the query.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class OrderingQueryOperator<TSource> : QueryOperator<TSource>
{
private readonly QueryOperator<TSource> _child;
private readonly OrdinalIndexState _ordinalIndexState;
public OrderingQueryOperator(QueryOperator<TSource> child, bool orderOn)
: base(orderOn, child.SpecifiedQuerySettings)
{
_child = child;
_ordinalIndexState = _child.OrdinalIndexState;
}
internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping)
{
return _child.Open(settings, preferStriping);
}
internal override IEnumerator<TSource> GetEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrderPreservation)
{
if (_child is ScanQueryOperator<TSource> childAsScan)
{
return childAsScan.Data.GetEnumerator();
}
return base.GetEnumerator(mergeOptions, suppressOrderPreservation);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
return _child.AsSequentialQuery(token);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _child.LimitsParallelism; }
}
internal override OrdinalIndexState OrdinalIndexState
{
get { return _ordinalIndexState; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderingQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Represents operators AsOrdered and AsUnordered. In the current implementation, it
/// simply turns on preservation globally in the query.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class OrderingQueryOperator<TSource> : QueryOperator<TSource>
{
private readonly QueryOperator<TSource> _child;
private readonly OrdinalIndexState _ordinalIndexState;
public OrderingQueryOperator(QueryOperator<TSource> child, bool orderOn)
: base(orderOn, child.SpecifiedQuerySettings)
{
_child = child;
_ordinalIndexState = _child.OrdinalIndexState;
}
internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping)
{
return _child.Open(settings, preferStriping);
}
internal override IEnumerator<TSource> GetEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrderPreservation)
{
if (_child is ScanQueryOperator<TSource> childAsScan)
{
return childAsScan.Data.GetEnumerator();
}
return base.GetEnumerator(mergeOptions, suppressOrderPreservation);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
return _child.AsSequentialQuery(token);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _child.LimitsParallelism; }
}
internal override OrdinalIndexState OrdinalIndexState
{
get { return _ordinalIndexState; }
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.ServiceModel.Syndication/tests/System/ServiceModel/Syndication/ReferencedCategoriesDocumentTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Xunit;
namespace System.ServiceModel.Syndication.Tests
{
public class ReferencedCategoriesDocumentTests
{
[Fact]
public void Ctor_Default()
{
var document = new ReferencedCategoriesDocument();
Assert.Empty(document.AttributeExtensions);
Assert.Null(document.BaseUri);
Assert.Empty(document.ElementExtensions);
Assert.Null(document.Language);
Assert.Null(document.Link);
}
public static IEnumerable<object[]> Ctor_Uri_TestData()
{
yield return new object[] { new Uri("http://microsoft.com") };
yield return new object[] { new Uri("/relative", UriKind.Relative) };
}
[Theory]
[MemberData(nameof(Ctor_Uri_TestData))]
public void Ctor_Uri(Uri link)
{
var document = new ReferencedCategoriesDocument(link);
Assert.Empty(document.AttributeExtensions);
Assert.Null(document.BaseUri);
Assert.Empty(document.ElementExtensions);
Assert.Null(document.Language);
Assert.Equal(link, document.Link);
}
[Fact]
public void Ctor_NullLink_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("link", () => new ReferencedCategoriesDocument(null));
}
[Fact]
public void Accepts_AddNonNullItem_Success()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
collection.Add("value");
Assert.Equal(1, collection.Count);
}
[Fact]
public void Accepts_AddNullItem_ThrowsArgumentNullException()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
AssertExtensions.Throws<ArgumentNullException>("item", () => collection.Add(null));
}
[Fact]
public void Accepts_SetNonNullItem_GetReturnsExpected()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
collection.Add("value");
collection[0] = "newValue";
Assert.Equal("newValue", collection[0]);
}
[Fact]
public void Accepts_SetNullItem_ThrowsArgumentNullException()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
collection.Add("value");
AssertExtensions.Throws<ArgumentNullException>("item", () => collection[0] = null);
}
[Fact]
public void Categories_AddNonNullItem_Success()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
collection.Add(new InlineCategoriesDocument());
Assert.Equal(1, collection.Count);
}
[Fact]
public void Categories_AddNullItem_ThrowsArgumentNullException()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
AssertExtensions.Throws<ArgumentNullException>("item", () => collection.Add(null));
}
[Fact]
public void Categories_SetNonNullItem_GetReturnsExpected()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
collection.Add(new InlineCategoriesDocument());
var newValue = new InlineCategoriesDocument();
collection[0] = newValue;
Assert.Same(newValue, collection[0]);
}
[Fact]
public void Categories_SetNullItem_ThrowsArgumentNullException()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
collection.Add(new InlineCategoriesDocument());
AssertExtensions.Throws<ArgumentNullException>("item", () => collection[0] = null);
}
[Theory]
[InlineData(null, null, null, null)]
[InlineData("", "", "", "")]
[InlineData("name", "ns", "value", "version")]
[InlineData("xmlns", "ns", "value", "version")]
[InlineData("name", "http://www.w3.org/2000/xmlns/", "value", "version")]
[InlineData("type", "ns", "value", "version")]
[InlineData("name", "http://www.w3.org/2001/XMLSchema-instance", "value", "version")]
public void TryParseAttribute_Invoke_ReturnsFalse(string name, string ns, string value, string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
Assert.False(document.TryParseAttributeEntryPoint(name, ns, value, version));
}
public static IEnumerable<object[]> TryParseElement_TestData()
{
yield return new object[] { null, null };
yield return new object[] { new XElement("name").CreateReader(), "" };
yield return new object[] { new XElement("name").CreateReader(), "version" };
}
[Theory]
[MemberData(nameof(TryParseElement_TestData))]
public void TryParseElement_Invoke_ReturnsFalse(XmlReader reader, string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
Assert.False(document.TryParseElementEntryPoint(reader, version));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("version")]
public void WriteAttributeExtensions_Invoke_ReturnsExpected(string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
CompareHelper.AssertEqualWriteOutput("", writer => document.WriteAttributeExtensionsEntryPoint(writer, version));
document.AttributeExtensions.Add(new XmlQualifiedName("name1"), "value");
document.AttributeExtensions.Add(new XmlQualifiedName("name2", "namespace"), "");
document.AttributeExtensions.Add(new XmlQualifiedName("name3"), null);
CompareHelper.AssertEqualWriteOutput(@"name1=""value"" d0p1:name2="""" name3=""""", writer => document.WriteAttributeExtensionsEntryPoint(writer, "version"));
}
[Fact]
public void WriteAttributeExtensions_NullWriter_ThrowsArgumentNullException()
{
var document = new ReferencedCategoriesDocumentSubclass();
AssertExtensions.Throws<ArgumentNullException>("writer", () => document.WriteAttributeExtensionsEntryPoint(null, "version"));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("version")]
public void WriteElementExtensions_Invoke_ReturnsExpected(string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
CompareHelper.AssertEqualWriteOutput("", writer => document.WriteElementExtensionsEntryPoint(writer, version));
document.ElementExtensions.Add(new ExtensionObject { Value = 10 });
document.ElementExtensions.Add(new ExtensionObject { Value = 11 });
CompareHelper.AssertEqualWriteOutput(
@"<ReferencedCategoriesDocumentTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</ReferencedCategoriesDocumentTests.ExtensionObject>
<ReferencedCategoriesDocumentTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>11</Value>
</ReferencedCategoriesDocumentTests.ExtensionObject>", writer => document.WriteElementExtensionsEntryPoint(writer, version));
}
[Fact]
public void WriteElementExtensions_NullWriter_ThrowsArgumentNullException()
{
var document = new ReferencedCategoriesDocumentSubclass();
AssertExtensions.Throws<ArgumentNullException>("writer", () => document.WriteElementExtensionsEntryPoint(null, "version"));
}
public class ReferencedCategoriesDocumentSubclass : ReferencedCategoriesDocument
{
public bool TryParseAttributeEntryPoint(string name, string ns, string value, string version) => TryParseAttribute(name, ns, value, version);
public bool TryParseElementEntryPoint(XmlReader reader, string version) => TryParseElement(reader, version);
public void WriteAttributeExtensionsEntryPoint(XmlWriter writer, string version) => WriteAttributeExtensions(writer, version);
public void WriteElementExtensionsEntryPoint(XmlWriter writer, string version) => WriteElementExtensions(writer, version);
}
[DataContract]
public class ExtensionObject
{
[DataMember]
public int Value { get; set; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using Xunit;
namespace System.ServiceModel.Syndication.Tests
{
public class ReferencedCategoriesDocumentTests
{
[Fact]
public void Ctor_Default()
{
var document = new ReferencedCategoriesDocument();
Assert.Empty(document.AttributeExtensions);
Assert.Null(document.BaseUri);
Assert.Empty(document.ElementExtensions);
Assert.Null(document.Language);
Assert.Null(document.Link);
}
public static IEnumerable<object[]> Ctor_Uri_TestData()
{
yield return new object[] { new Uri("http://microsoft.com") };
yield return new object[] { new Uri("/relative", UriKind.Relative) };
}
[Theory]
[MemberData(nameof(Ctor_Uri_TestData))]
public void Ctor_Uri(Uri link)
{
var document = new ReferencedCategoriesDocument(link);
Assert.Empty(document.AttributeExtensions);
Assert.Null(document.BaseUri);
Assert.Empty(document.ElementExtensions);
Assert.Null(document.Language);
Assert.Equal(link, document.Link);
}
[Fact]
public void Ctor_NullLink_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("link", () => new ReferencedCategoriesDocument(null));
}
[Fact]
public void Accepts_AddNonNullItem_Success()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
collection.Add("value");
Assert.Equal(1, collection.Count);
}
[Fact]
public void Accepts_AddNullItem_ThrowsArgumentNullException()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
AssertExtensions.Throws<ArgumentNullException>("item", () => collection.Add(null));
}
[Fact]
public void Accepts_SetNonNullItem_GetReturnsExpected()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
collection.Add("value");
collection[0] = "newValue";
Assert.Equal("newValue", collection[0]);
}
[Fact]
public void Accepts_SetNullItem_ThrowsArgumentNullException()
{
Collection<string> collection = new ResourceCollectionInfo().Accepts;
collection.Add("value");
AssertExtensions.Throws<ArgumentNullException>("item", () => collection[0] = null);
}
[Fact]
public void Categories_AddNonNullItem_Success()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
collection.Add(new InlineCategoriesDocument());
Assert.Equal(1, collection.Count);
}
[Fact]
public void Categories_AddNullItem_ThrowsArgumentNullException()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
AssertExtensions.Throws<ArgumentNullException>("item", () => collection.Add(null));
}
[Fact]
public void Categories_SetNonNullItem_GetReturnsExpected()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
collection.Add(new InlineCategoriesDocument());
var newValue = new InlineCategoriesDocument();
collection[0] = newValue;
Assert.Same(newValue, collection[0]);
}
[Fact]
public void Categories_SetNullItem_ThrowsArgumentNullException()
{
Collection<CategoriesDocument> collection = new ResourceCollectionInfo().Categories;
collection.Add(new InlineCategoriesDocument());
AssertExtensions.Throws<ArgumentNullException>("item", () => collection[0] = null);
}
[Theory]
[InlineData(null, null, null, null)]
[InlineData("", "", "", "")]
[InlineData("name", "ns", "value", "version")]
[InlineData("xmlns", "ns", "value", "version")]
[InlineData("name", "http://www.w3.org/2000/xmlns/", "value", "version")]
[InlineData("type", "ns", "value", "version")]
[InlineData("name", "http://www.w3.org/2001/XMLSchema-instance", "value", "version")]
public void TryParseAttribute_Invoke_ReturnsFalse(string name, string ns, string value, string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
Assert.False(document.TryParseAttributeEntryPoint(name, ns, value, version));
}
public static IEnumerable<object[]> TryParseElement_TestData()
{
yield return new object[] { null, null };
yield return new object[] { new XElement("name").CreateReader(), "" };
yield return new object[] { new XElement("name").CreateReader(), "version" };
}
[Theory]
[MemberData(nameof(TryParseElement_TestData))]
public void TryParseElement_Invoke_ReturnsFalse(XmlReader reader, string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
Assert.False(document.TryParseElementEntryPoint(reader, version));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("version")]
public void WriteAttributeExtensions_Invoke_ReturnsExpected(string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
CompareHelper.AssertEqualWriteOutput("", writer => document.WriteAttributeExtensionsEntryPoint(writer, version));
document.AttributeExtensions.Add(new XmlQualifiedName("name1"), "value");
document.AttributeExtensions.Add(new XmlQualifiedName("name2", "namespace"), "");
document.AttributeExtensions.Add(new XmlQualifiedName("name3"), null);
CompareHelper.AssertEqualWriteOutput(@"name1=""value"" d0p1:name2="""" name3=""""", writer => document.WriteAttributeExtensionsEntryPoint(writer, "version"));
}
[Fact]
public void WriteAttributeExtensions_NullWriter_ThrowsArgumentNullException()
{
var document = new ReferencedCategoriesDocumentSubclass();
AssertExtensions.Throws<ArgumentNullException>("writer", () => document.WriteAttributeExtensionsEntryPoint(null, "version"));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("version")]
public void WriteElementExtensions_Invoke_ReturnsExpected(string version)
{
var document = new ReferencedCategoriesDocumentSubclass();
CompareHelper.AssertEqualWriteOutput("", writer => document.WriteElementExtensionsEntryPoint(writer, version));
document.ElementExtensions.Add(new ExtensionObject { Value = 10 });
document.ElementExtensions.Add(new ExtensionObject { Value = 11 });
CompareHelper.AssertEqualWriteOutput(
@"<ReferencedCategoriesDocumentTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</ReferencedCategoriesDocumentTests.ExtensionObject>
<ReferencedCategoriesDocumentTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>11</Value>
</ReferencedCategoriesDocumentTests.ExtensionObject>", writer => document.WriteElementExtensionsEntryPoint(writer, version));
}
[Fact]
public void WriteElementExtensions_NullWriter_ThrowsArgumentNullException()
{
var document = new ReferencedCategoriesDocumentSubclass();
AssertExtensions.Throws<ArgumentNullException>("writer", () => document.WriteElementExtensionsEntryPoint(null, "version"));
}
public class ReferencedCategoriesDocumentSubclass : ReferencedCategoriesDocument
{
public bool TryParseAttributeEntryPoint(string name, string ns, string value, string version) => TryParseAttribute(name, ns, value, version);
public bool TryParseElementEntryPoint(XmlReader reader, string version) => TryParseElement(reader, version);
public void WriteAttributeExtensionsEntryPoint(XmlWriter writer, string version) => WriteAttributeExtensions(writer, version);
public void WriteElementExtensionsEntryPoint(XmlWriter writer, string version) => WriteElementExtensions(writer, version);
}
[DataContract]
public class ExtensionObject
{
[DataMember]
public int Value { get; set; }
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ExtractNarrowingSaturateUpper.Vector128.UInt16.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.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 ExtractNarrowingSaturateUpper_Vector128_UInt16()
{
var test = new SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16
{
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(UInt16[] inArray1, UInt32[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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<UInt16> _fld1;
public Vector128<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16 testClass)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16 testClass)
{
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(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<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector64<UInt16> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector64<UInt16> _fld1;
private Vector128<UInt32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[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.ExtractNarrowingSaturateUpper(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingSaturateUpper), new Type[] { typeof(Vector64<UInt16>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingSaturateUpper), new Type[] { typeof(Vector64<UInt16>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ExtractNarrowingSaturateUpper(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pClsVar1)),
AdvSimd.LoadVector128((UInt32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ExtractNarrowingSaturateUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ExtractNarrowingSaturateUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16();
var result = AdvSimd.ExtractNarrowingSaturateUpper(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__ExtractNarrowingSaturateUpper_Vector128_UInt16();
fixed (Vector64<UInt16>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ExtractNarrowingSaturateUpper(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingSaturateUpper(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(&test._fld1)),
AdvSimd.LoadVector128((UInt32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt32[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ExtractNarrowingSaturateUpper(left, right, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractNarrowingSaturateUpper)}<UInt16>(Vector64<UInt16>, Vector128<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.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 ExtractNarrowingSaturateUpper_Vector128_UInt16()
{
var test = new SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16
{
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(UInt16[] inArray1, UInt32[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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<UInt16> _fld1;
public Vector128<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16 testClass)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16 testClass)
{
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(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<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector64<UInt16> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector64<UInt16> _fld1;
private Vector128<UInt32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[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.ExtractNarrowingSaturateUpper(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingSaturateUpper), new Type[] { typeof(Vector64<UInt16>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingSaturateUpper), new Type[] { typeof(Vector64<UInt16>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ExtractNarrowingSaturateUpper(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pClsVar1)),
AdvSimd.LoadVector128((UInt32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ExtractNarrowingSaturateUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ExtractNarrowingSaturateUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ExtractNarrowingSaturateUpper_Vector128_UInt16();
var result = AdvSimd.ExtractNarrowingSaturateUpper(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__ExtractNarrowingSaturateUpper_Vector128_UInt16();
fixed (Vector64<UInt16>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ExtractNarrowingSaturateUpper(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingSaturateUpper(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingSaturateUpper(
AdvSimd.LoadVector64((UInt16*)(&test._fld1)),
AdvSimd.LoadVector128((UInt32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt32[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ExtractNarrowingSaturateUpper(left, right, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractNarrowingSaturateUpper)}<UInt16>(Vector64<UInt16>, Vector128<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.xml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Collections.Generic;
using System.Formats.Asn1;
using System.Runtime.InteropServices;
namespace System.Security.Cryptography.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal partial struct AttributeAsn
{
internal string AttrType;
internal ReadOnlyMemory<byte>[] AttrValues;
internal void Encode(AsnWriter writer)
{
Encode(writer, Asn1Tag.Sequence);
}
internal void Encode(AsnWriter writer, Asn1Tag tag)
{
writer.PushSequence(tag);
try
{
writer.WriteObjectIdentifier(AttrType);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
writer.PushSetOf();
for (int i = 0; i < AttrValues.Length; i++)
{
try
{
writer.WriteEncodedValue(AttrValues[i].Span);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
writer.PopSetOf();
writer.PopSequence(tag);
}
internal static AttributeAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
return Decode(Asn1Tag.Sequence, encoded, ruleSet);
}
internal static AttributeAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
try
{
AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet);
DecodeCore(ref reader, expectedTag, encoded, out AttributeAsn decoded);
reader.ThrowIfNotEmpty();
return decoded;
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out AttributeAsn decoded)
{
Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded);
}
internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out AttributeAsn decoded)
{
try
{
DecodeCore(ref reader, expectedTag, rebind, out decoded);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out AttributeAsn decoded)
{
decoded = default;
AsnValueReader sequenceReader = reader.ReadSequence(expectedTag);
AsnValueReader collectionReader;
ReadOnlySpan<byte> rebindSpan = rebind.Span;
int offset;
ReadOnlySpan<byte> tmpSpan;
decoded.AttrType = sequenceReader.ReadObjectIdentifier();
// Decode SEQUENCE OF for AttrValues
{
collectionReader = sequenceReader.ReadSetOf();
var tmpList = new List<ReadOnlyMemory<byte>>();
ReadOnlyMemory<byte> tmpItem;
while (collectionReader.HasData)
{
tmpSpan = collectionReader.ReadEncodedValue();
tmpItem = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
tmpList.Add(tmpItem);
}
decoded.AttrValues = tmpList.ToArray();
}
sequenceReader.ThrowIfNotEmpty();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Collections.Generic;
using System.Formats.Asn1;
using System.Runtime.InteropServices;
namespace System.Security.Cryptography.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal partial struct AttributeAsn
{
internal string AttrType;
internal ReadOnlyMemory<byte>[] AttrValues;
internal void Encode(AsnWriter writer)
{
Encode(writer, Asn1Tag.Sequence);
}
internal void Encode(AsnWriter writer, Asn1Tag tag)
{
writer.PushSequence(tag);
try
{
writer.WriteObjectIdentifier(AttrType);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
writer.PushSetOf();
for (int i = 0; i < AttrValues.Length; i++)
{
try
{
writer.WriteEncodedValue(AttrValues[i].Span);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
writer.PopSetOf();
writer.PopSequence(tag);
}
internal static AttributeAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
return Decode(Asn1Tag.Sequence, encoded, ruleSet);
}
internal static AttributeAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
try
{
AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet);
DecodeCore(ref reader, expectedTag, encoded, out AttributeAsn decoded);
reader.ThrowIfNotEmpty();
return decoded;
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out AttributeAsn decoded)
{
Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded);
}
internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out AttributeAsn decoded)
{
try
{
DecodeCore(ref reader, expectedTag, rebind, out decoded);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out AttributeAsn decoded)
{
decoded = default;
AsnValueReader sequenceReader = reader.ReadSequence(expectedTag);
AsnValueReader collectionReader;
ReadOnlySpan<byte> rebindSpan = rebind.Span;
int offset;
ReadOnlySpan<byte> tmpSpan;
decoded.AttrType = sequenceReader.ReadObjectIdentifier();
// Decode SEQUENCE OF for AttrValues
{
collectionReader = sequenceReader.ReadSetOf();
var tmpList = new List<ReadOnlyMemory<byte>>();
ReadOnlyMemory<byte> tmpItem;
while (collectionReader.HasData)
{
tmpSpan = collectionReader.ReadEncodedValue();
tmpItem = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
tmpList.Add(tmpItem);
}
decoded.AttrValues = tmpList.ToArray();
}
sequenceReader.ThrowIfNotEmpty();
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Xml.Schema;
using System.Xml.Extensions;
using System.Diagnostics.CodeAnalysis;
namespace System.Xml.Serialization
{
internal sealed class XmlSerializationWriterILGen : XmlSerializationILGen
{
[RequiresUnreferencedCode("creates XmlSerializationILGen")]
internal XmlSerializationWriterILGen(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(XmlSerializationWriter),
Type.EmptyTypes);
foreach (TypeScope scope in Scopes)
{
foreach (TypeMapping mapping in scope.TypeMappings)
{
if (mapping is StructMapping || mapping is EnumMapping)
{
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);
}
}
[RequiresUnreferencedCode("calls GenerateReferencedMethods")]
internal Type GenerateEnd()
{
GenerateReferencedMethods();
GenerateInitCallbacksMethod();
this.typeBuilder.DefineDefaultConstructor(
CodeGenerator.PublicMethodAttributes);
return this.typeBuilder.CreateTypeInfo()!.AsType();
}
[RequiresUnreferencedCode("calls GenerateTypeElement")]
internal string? GenerateElement(XmlMapping xmlMapping)
{
if (!xmlMapping.IsWriteable)
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));
}
private void GenerateInitCallbacksMethod()
{
ilg = new CodeGenerator(this.typeBuilder);
ilg.BeginMethod(typeof(void), "InitCallbacks", Type.EmptyTypes, Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.EndMethod();
}
[RequiresUnreferencedCode("calls Load")]
private void WriteQualifiedNameElement(string name, string? ns, object? defaultValue, SourceInfo source, bool nullable, TypeMapping mapping)
{
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value;
if (hasDefault)
{
throw Globals.NotSupported("XmlQualifiedName DefaultValue not supported. Fail in WriteValue()");
}
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
argTypes.Add(typeof(string));
if (ns != null)
{
ilg.Ldstr(GetCSharpString(ns));
argTypes.Add(typeof(string));
}
source.Load(mapping.TypeDesc!.Type!);
argTypes.Add(mapping.TypeDesc.Type!);
MethodInfo XmlSerializationWriter_WriteXXX = typeof(XmlSerializationWriter).GetMethod(
nullable ? ("WriteNullableQualifiedNameLiteral") : "WriteElementQualifiedName",
CodeGenerator.InstanceBindingFlags,
argTypes.ToArray()
)!;
ilg.Call(XmlSerializationWriter_WriteXXX);
}
[RequiresUnreferencedCode("calls Load")]
private void WriteEnumValue(EnumMapping mapping, SourceInfo source, out Type returnType)
{
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
// For enum, its write method (eg. Write1_Gender) could be called multiple times
// prior to its declaration.
MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(string),
new Type[] { mapping.TypeDesc!.Type! });
ilg.Ldarg(0);
source.Load(mapping.TypeDesc.Type!);
ilg.Call(methodBuilder);
returnType = typeof(string);
}
[RequiresUnreferencedCode("calls Load")]
private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type returnType)
{
if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String")
{
source.Load(typeDesc.Type!);
returnType = typeDesc.Type!;
}
else
{
if (!typeDesc.HasCustomFormatter)
{
Type argType = typeDesc.Type!;
// No ToString(Byte), compiler used ToString(Int16) instead.
if (argType == typeof(byte))
argType = typeof(short);
// No ToString(UInt16), compiler used ToString(Int32) instead.
else if (argType == typeof(ushort))
argType = typeof(int);
MethodInfo XmlConvert_ToString = typeof(XmlConvert).GetMethod(
"ToString",
CodeGenerator.StaticBindingFlags,
new Type[] { argType }
)!;
source.Load(typeDesc.Type!);
ilg.Call(XmlConvert_ToString);
returnType = XmlConvert_ToString.ReturnType;
}
else
{
// Only these methods below that is non Static and need to ldarg("this") for Call.
BindingFlags bindingFlags = CodeGenerator.StaticBindingFlags;
if (typeDesc.FormatterName == "XmlQualifiedName")
{
bindingFlags = CodeGenerator.InstanceBindingFlags;
ilg.Ldarg(0);
}
MethodInfo FromXXX = typeof(XmlSerializationWriter).GetMethod(
$"From{typeDesc.FormatterName}",
bindingFlags,
new Type[] { typeDesc.Type! }
)!;
source.Load(typeDesc.Type!);
ilg.Call(FromXXX);
returnType = FromXXX.ReturnType;
}
}
}
[RequiresUnreferencedCode("Calls WriteCheckDefault")]
private void WritePrimitive(string method, string name, string? ns, object? defaultValue, SourceInfo source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable)
{
TypeDesc typeDesc = mapping.TypeDesc!;
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport;
if (hasDefault)
{
if (mapping is EnumMapping)
{
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (defaultValue!.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name));
#endif
source.Load(mapping.TypeDesc!.Type!);
string? enumDefaultValue = null;
if (((EnumMapping)mapping).IsFlags)
{
string[] values = ((string)defaultValue!).Split(null);
for (int i = 0; i < values.Length; i++)
{
if (values[i] == null || values[i].Length == 0)
continue;
if (i > 0)
enumDefaultValue += ", ";
enumDefaultValue += values[i];
}
}
else
{
enumDefaultValue = (string)defaultValue!;
}
ilg.Ldc(Enum.Parse(mapping.TypeDesc.Type!, enumDefaultValue!, false));
ilg.If(Cmp.NotEqualTo); // " != "
}
else
{
WriteCheckDefault(source, defaultValue!, isNullable);
}
}
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
argTypes.Add(typeof(string));
ilg.Ldstr(GetCSharpString(name));
if (ns != null)
{
argTypes.Add(typeof(string));
ilg.Ldstr(GetCSharpString(ns));
}
Type argType;
if (mapping is EnumMapping)
{
WriteEnumValue((EnumMapping)mapping, source, out argType);
argTypes.Add(argType);
}
else
{
WritePrimitiveValue(typeDesc, source, out argType);
argTypes.Add(argType);
}
if (writeXsiType)
{
argTypes.Add(typeof(XmlQualifiedName));
ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.New(XmlQualifiedName_ctor);
}
MethodInfo XmlSerializationWriter_method = typeof(XmlSerializationWriter).GetMethod(
method,
CodeGenerator.InstanceBindingFlags,
argTypes.ToArray()
)!;
ilg.Call(XmlSerializationWriter_method);
if (hasDefault)
{
ilg.EndIf();
}
}
[RequiresUnreferencedCode("XmlSerializationWriter methods have RequiresUnreferencedCode")]
private void WriteTag(string methodName, string name, string? ns)
{
MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod(
methodName,
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Call(XmlSerializationWriter_Method);
}
[RequiresUnreferencedCode("XmlSerializationWriter methods have RequiresUnreferencedCode")]
private void WriteTag(string methodName, string name, string? ns, bool writePrefixed)
{
MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod(
methodName,
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Load(null);
ilg.Ldc(writePrefixed);
ilg.Call(XmlSerializationWriter_Method);
}
[RequiresUnreferencedCode("calls WriteTag")]
private void WriteStartElement(string name, string? ns, bool writePrefixed)
{
WriteTag("WriteStartElement", name, ns, writePrefixed);
}
private void WriteEndElement()
{
MethodInfo XmlSerializationWriter_WriteEndElement = typeof(XmlSerializationWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_WriteEndElement);
}
private void WriteEndElement(string source)
{
MethodInfo XmlSerializationWriter_WriteEndElement = typeof(XmlSerializationWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
)!;
object oVar = ilg.GetVariable(source);
ilg.Ldarg(0);
ilg.Load(oVar);
ilg.ConvertValue(ilg.GetVariableType(oVar), typeof(object));
ilg.Call(XmlSerializationWriter_WriteEndElement);
}
[RequiresUnreferencedCode("calls WriteTag")]
private void WriteLiteralNullTag(string name, string? ns)
{
WriteTag("WriteNullTagLiteral", name, ns);
}
[RequiresUnreferencedCode("calls WriteTag")]
private void WriteEmptyTag(string name, string? ns)
{
WriteTag("WriteEmptyTag", name, ns);
}
[RequiresUnreferencedCode("calls WriteMember")]
private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping)
{
ElementAccessor element = xmlMembersMapping.Accessor;
MembersMapping mapping = (MembersMapping)element.Mapping!;
bool hasWrapperElement = mapping.HasWrapperElement;
bool writeAccessors = mapping.WriteAccessors;
string methodName = NextMethodName(element.Name);
ilg = new CodeGenerator(this.typeBuilder);
ilg.BeginMethod(
typeof(void),
methodName,
new Type[] { typeof(object[]) },
new string[] { "p" },
CodeGenerator.PublicMethodAttributes
);
MethodInfo XmlSerializationWriter_WriteStartDocument = typeof(XmlSerializationWriter).GetMethod(
"WriteStartDocument",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_WriteStartDocument);
MethodInfo XmlSerializationWriter_TopLevelElement = typeof(XmlSerializationWriter).GetMethod(
"TopLevelElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_TopLevelElement);
// in the top-level method add check for the parameters length,
// because visual basic does not have a concept of an <out> parameter it uses <ByRef> instead
// so sometime we think that we have more parameters then supplied
LocalBuilder pLengthLoc = ilg.DeclareLocal(typeof(int), "pLength");
ilg.Ldarg("p");
ilg.Ldlen();
ilg.Stloc(pLengthLoc);
if (hasWrapperElement)
{
WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""), false);
int xmlnsMember = FindXmlnsIndex(mapping.Members!);
if (xmlnsMember >= 0)
{
string source = string.Create(CultureInfo.InvariantCulture, $"(({typeof(XmlSerializerNamespaces).FullName})p[{xmlnsMember}])");
ilg.Ldloc(pLengthLoc);
ilg.Ldc(xmlnsMember);
ilg.If(Cmp.GreaterThan);
WriteNamespaces(source);
ilg.EndIf();
}
for (int i = 0; i < mapping.Members!.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Attribute != null && !member.Ignore)
{
SourceInfo source = new SourceInfo($"p[{i}]", null, null, pLengthLoc.LocalType.GetElementType()!, ilg);
SourceInfo? specifiedSource = null;
int specifiedPosition = 0;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = $"{member.Name}Specified";
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = new SourceInfo($"((bool)p[{j}])", null, null, typeof(bool), ilg);
specifiedPosition = j;
break;
}
}
}
ilg.Ldloc(pLengthLoc);
ilg.Ldc(i);
ilg.If(Cmp.GreaterThan);
if (specifiedSource != null)
{
Label labelTrue = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
ilg.Ldloc(pLengthLoc);
ilg.Ldc(specifiedPosition);
ilg.Ble(labelTrue);
specifiedSource.Load(typeof(bool));
ilg.Br_S(labelEnd);
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
ilg.MarkLabel(labelEnd);
ilg.If();
}
WriteMember(source, member.Attribute, member.TypeDesc!, "p");
if (specifiedSource != null)
{
ilg.EndIf();
}
ilg.EndIf();
}
}
}
for (int i = 0; i < mapping.Members!.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Xmlns != null)
continue;
if (member.Ignore)
continue;
SourceInfo? specifiedSource = null;
int specifiedPosition = 0;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = $"{member.Name}Specified";
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = new SourceInfo($"((bool)p[{j}])", null, null, typeof(bool), ilg);
specifiedPosition = j;
break;
}
}
}
ilg.Ldloc(pLengthLoc);
ilg.Ldc(i);
ilg.If(Cmp.GreaterThan);
if (specifiedSource != null)
{
Label labelTrue = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
ilg.Ldloc(pLengthLoc);
ilg.Ldc(specifiedPosition);
ilg.Ble(labelTrue);
specifiedSource.Load(typeof(bool));
ilg.Br_S(labelEnd);
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
ilg.MarkLabel(labelEnd);
ilg.If();
}
string source = $"p[{i}]";
string? enumSource = null;
if (member.ChoiceIdentifier != null)
{
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName)
{
enumSource = $"(({mapping.Members[j].TypeDesc!.CSharpName})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 (enumSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping."));
#endif
}
// override writeAccessors choice when we've written a wrapper element
WriteMember(new SourceInfo(source, source, null, null, ilg), enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement);
if (specifiedSource != null)
{
ilg.EndIf();
}
ilg.EndIf();
}
if (hasWrapperElement)
{
WriteEndElement();
}
ilg.EndMethod();
return methodName;
}
[RequiresUnreferencedCode("calls WriteMember")]
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(void),
methodName,
new Type[] { typeof(object) },
new string[] { "o" },
CodeGenerator.PublicMethodAttributes
);
MethodInfo XmlSerializationWriter_WriteStartDocument = typeof(XmlSerializationWriter).GetMethod(
"WriteStartDocument",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_WriteStartDocument);
ilg.If(ilg.GetArg("o"), Cmp.EqualTo, null);
if (element.IsNullable)
{
WriteLiteralNullTag(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""));
}
else
WriteEmptyTag(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""));
ilg.GotoMethodEnd();
ilg.EndIf();
if (!mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive)
{
MethodInfo XmlSerializationWriter_TopLevelElement = typeof(XmlSerializationWriter).GetMethod(
"TopLevelElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_TopLevelElement);
}
WriteMember(new SourceInfo("o", "o", null, typeof(object), ilg), null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, true);
ilg.EndMethod();
return methodName;
}
private string NextMethodName(string name)
{
return string.Create(CultureInfo.InvariantCulture, $"Write{++NextMethodNumber}_{CodeIdentifier.MakeValidInternal(name)}");
}
private void WriteEnumMethod(EnumMapping mapping)
{
string? methodName;
MethodNames.TryGetValue(mapping, out methodName);
List<Type> argTypes = new List<Type>();
List<string> argNames = new List<string>();
argTypes.Add(mapping.TypeDesc!.Type!);
argNames.Add("v");
ilg = new CodeGenerator(this.typeBuilder);
ilg.BeginMethod(
typeof(string),
GetMethodBuilder(methodName!),
argTypes.ToArray(),
argNames.ToArray(),
CodeGenerator.PrivateMethodAttributes);
LocalBuilder sLoc = ilg.DeclareLocal(typeof(string), "s");
ilg.Load(null);
ilg.Stloc(sLoc);
ConstantMapping[] constants = mapping.Constants!;
if (constants.Length > 0)
{
var values = new HashSet<long>();
List<Label> caseLabels = new List<Label>();
List<string> retValues = new List<string>();
Label defaultLabel = ilg.DefineLabel();
Label endSwitchLabel = ilg.DefineLabel();
// This local is necessary; otherwise, it becomes if/else
LocalBuilder localTmp = ilg.DeclareLocal(mapping.TypeDesc.Type!, "localTmp");
ilg.Ldarg("v");
ilg.Stloc(localTmp);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
if (values.Add(c.Value))
{
Label caseLabel = ilg.DefineLabel();
ilg.Ldloc(localTmp);
ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type!, c.Value));
ilg.Beq(caseLabel);
caseLabels.Add(caseLabel);
retValues.Add(GetCSharpString(c.XmlName));
}
}
if (mapping.IsFlags)
{
ilg.Br(defaultLabel);
for (int i = 0; i < caseLabels.Count; i++)
{
ilg.MarkLabel(caseLabels[i]);
ilg.Ldc(retValues[i]);
ilg.Stloc(sLoc);
ilg.Br(endSwitchLabel);
}
ilg.MarkLabel(defaultLabel);
RaCodeGen.ILGenForEnumLongValue(ilg, "v");
LocalBuilder strArray = ilg.DeclareLocal(typeof(string[]), "strArray");
ilg.NewArray(typeof(string), constants.Length);
ilg.Stloc(strArray);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
ilg.Ldloc(strArray);
ilg.Ldc(i);
ilg.Ldstr(GetCSharpString(c.XmlName));
ilg.Stelem(typeof(string));
}
ilg.Ldloc(strArray);
LocalBuilder longArray = ilg.DeclareLocal(typeof(long[]), "longArray");
ilg.NewArray(typeof(long), constants.Length);
ilg.Stloc(longArray);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
ilg.Ldloc(longArray);
ilg.Ldc(i);
ilg.Ldc(c.Value);
ilg.Stelem(typeof(long));
}
ilg.Ldloc(longArray);
ilg.Ldstr(GetCSharpString(mapping.TypeDesc.FullName));
MethodInfo XmlSerializationWriter_FromEnum = typeof(XmlSerializationWriter).GetMethod(
"FromEnum",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(long), typeof(string[]), typeof(long[]), typeof(string) }
)!;
ilg.Call(XmlSerializationWriter_FromEnum);
ilg.Stloc(sLoc);
ilg.Br(endSwitchLabel);
}
else
{
ilg.Br(defaultLabel);
// Case bodies
for (int i = 0; i < caseLabels.Count; i++)
{
ilg.MarkLabel(caseLabels[i]);
ilg.Ldc(retValues[i]);
ilg.Stloc(sLoc);
ilg.Br(endSwitchLabel);
}
MethodInfo CultureInfo_get_InvariantCulture = typeof(CultureInfo).GetMethod(
"get_InvariantCulture",
CodeGenerator.StaticBindingFlags,
Type.EmptyTypes
)!;
MethodInfo Int64_ToString = typeof(long).GetMethod(
"ToString",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(IFormatProvider) }
)!;
MethodInfo XmlSerializationWriter_CreateInvalidEnumValueException = typeof(XmlSerializationWriter).GetMethod(
"CreateInvalidEnumValueException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object), typeof(string) }
)!;
// Default body
ilg.MarkLabel(defaultLabel);
ilg.Ldarg(0);
ilg.Ldarg("v");
ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long));
LocalBuilder numLoc = ilg.DeclareLocal(typeof(long), "num");
ilg.Stloc(numLoc);
// Invoke method on Value type need address
ilg.LdlocAddress(numLoc);
ilg.Call(CultureInfo_get_InvariantCulture);
ilg.Call(Int64_ToString);
ilg.Ldstr(GetCSharpString(mapping.TypeDesc.FullName));
ilg.Call(XmlSerializationWriter_CreateInvalidEnumValueException);
ilg.Throw();
}
ilg.MarkLabel(endSwitchLabel);
}
ilg.Ldloc(sLoc);
ilg.EndMethod();
}
private void WriteDerivedTypes(StructMapping mapping)
{
for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
ilg.InitElseIf();
WriteTypeCompare("t", derived.TypeDesc!.Type!);
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("derived from " + mapping.TypeDesc!.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name));
#endif
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
argTypes.Add(typeof(string));
ilg.Ldarg("n");
argTypes.Add(typeof(string));
ilg.Ldarg("ns");
object oVar = ilg.GetVariable("o");
Type oType = ilg.GetVariableType(oVar);
ilg.Load(oVar);
ilg.ConvertValue(oType, derived.TypeDesc.Type!);
argTypes.Add(derived.TypeDesc.Type!);
if (derived.TypeDesc.IsNullable)
{
argTypes.Add(typeof(bool));
ilg.Ldarg("isNullable");
}
argTypes.Add(typeof(bool));
ilg.Ldc(true);
MethodInfo methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(void),
argTypes.ToArray());
ilg.Call(methodBuilder);
ilg.GotoMethodEnd();
WriteDerivedTypes(derived);
}
}
[RequiresUnreferencedCode("calls WriteMember")]
private void WriteEnumAndArrayTypes()
{
foreach (TypeScope scope in Scopes)
{
foreach (Mapping m in scope.TypeMappings)
{
if (m is EnumMapping)
{
EnumMapping mapping = (EnumMapping)m;
ilg.InitElseIf();
WriteTypeCompare("t", mapping.TypeDesc!.Type!);
// WriteXXXTypeCompare leave bool on the stack
ilg.AndIf();
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
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod(
"WriteStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Call(XmlWriter_WriteStartElement);
MethodInfo XmlSerializationWriter_WriteXsiType = typeof(XmlSerializationWriter).GetMethod(
"WriteXsiType",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.Call(XmlSerializationWriter_WriteXsiType);
MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(string),
new Type[] { mapping.TypeDesc.Type! }
);
MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod(
"WriteString",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
object oVar = ilg.GetVariable("o");
ilg.Ldarg(0);
ilg.Load(oVar);
ilg.ConvertValue(ilg.GetVariableType(oVar), mapping.TypeDesc.Type!);
ilg.Call(methodBuilder);
ilg.Call(XmlWriter_WriteString);
MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(XmlWriter_WriteEndElement);
ilg.GotoMethodEnd();
}
else if (m is ArrayMapping)
{
ArrayMapping? mapping = m as ArrayMapping;
if (mapping == null) continue;
ilg.InitElseIf();
if (mapping.TypeDesc!.IsArray)
WriteArrayTypeCompare("t", mapping.TypeDesc.Type!);
else
WriteTypeCompare("t", mapping.TypeDesc.Type!);
// WriteXXXTypeCompare leave bool on the stack
ilg.AndIf();
ilg.EnterScope();
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod(
"WriteStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Call(XmlWriter_WriteStartElement);
MethodInfo XmlSerializationWriter_WriteXsiType = typeof(XmlSerializationWriter).GetMethod(
"WriteXsiType",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.Call(XmlSerializationWriter_WriteXsiType);
WriteMember(new SourceInfo("o", "o", null, null, ilg), null, mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, true);
MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(XmlWriter_WriteEndElement);
ilg.GotoMethodEnd();
ilg.ExitScope();
}
}
}
}
[RequiresUnreferencedCode("Calls WriteMember")]
private void WriteStructMethod(StructMapping mapping)
{
string? methodName;
MethodNames.TryGetValue(mapping, out methodName);
ilg = new CodeGenerator(this.typeBuilder);
List<Type> argTypes = new List<Type>(5);
List<string> argNames = new List<string>(5);
argTypes.Add(typeof(string));
argNames.Add("n");
argTypes.Add(typeof(string));
argNames.Add("ns");
argTypes.Add(mapping.TypeDesc!.Type!);
argNames.Add("o");
if (mapping.TypeDesc.IsNullable)
{
argTypes.Add(typeof(bool));
argNames.Add("isNullable");
}
argTypes.Add(typeof(bool));
argNames.Add("needType");
ilg.BeginMethod(typeof(void),
GetMethodBuilder(methodName!),
argTypes.ToArray(),
argNames.ToArray(),
CodeGenerator.PrivateMethodAttributes);
if (mapping.TypeDesc.IsNullable)
{
ilg.If(ilg.GetArg("o"), Cmp.EqualTo, null);
{
ilg.If(ilg.GetArg("isNullable"), Cmp.EqualTo, true);
{
MethodInfo XmlSerializationWriter_WriteNullTagLiteral = typeof(XmlSerializationWriter).GetMethod(
"WriteNullTagLiteral",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Call(XmlSerializationWriter_WriteNullTagLiteral);
}
ilg.EndIf();
ilg.GotoMethodEnd();
}
ilg.EndIf();
}
ilg.If(ilg.GetArg("needType"), Cmp.NotEqualTo, true); // if (!needType)
LocalBuilder tLoc = ilg.DeclareLocal(typeof(Type), "t");
MethodInfo Object_GetType = typeof(object).GetMethod(
"GetType",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ArgBuilder oArg = ilg.GetArg("o");
ilg.LdargAddress(oArg);
ilg.ConvertAddress(oArg.ArgType, typeof(object));
ilg.Call(Object_GetType);
ilg.Stloc(tLoc);
WriteTypeCompare("t", mapping.TypeDesc.Type!);
// Bool on the stack from WriteTypeCompare.
ilg.If(); // if (t == typeof(...))
WriteDerivedTypes(mapping);
if (mapping.TypeDesc.IsRoot)
WriteEnumAndArrayTypes();
ilg.Else();
if (mapping.TypeDesc.IsRoot)
{
MethodInfo XmlSerializationWriter_WriteTypedPrimitive = typeof(XmlSerializationWriter).GetMethod(
"WriteTypedPrimitive",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) }
)!;
ilg.Ldarg(0);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Ldarg("o");
ilg.Ldc(true);
ilg.Call(XmlSerializationWriter_WriteTypedPrimitive);
ilg.GotoMethodEnd();
}
else
{
MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
)!;
ilg.Ldarg(0);
ilg.Ldarg(oArg);
ilg.ConvertValue(oArg.ArgType, typeof(object));
ilg.Call(XmlSerializationWriter_CreateUnknownTypeException);
ilg.Throw();
}
ilg.EndIf(); // if (t == typeof(...))
ilg.EndIf(); // if (!needType)
if (!mapping.TypeDesc.IsAbstract)
{
if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type))
{
MethodInfo XmlSerializationWriter_set_EscapeName = typeof(XmlSerializationWriter).GetMethod(
"set_EscapeName",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(bool) }
)!;
ilg.Ldarg(0);
ilg.Ldc(false);
ilg.Call(XmlSerializationWriter_set_EscapeName);
}
string? xmlnsSource = null;
MemberMapping[] members = TypeScope.GetAllMembers(mapping, memberInfos);
int xmlnsMember = FindXmlnsIndex(members);
if (xmlnsMember >= 0)
{
MemberMapping member = members[xmlnsMember];
CodeIdentifier.CheckValidIdentifier(member.Name);
xmlnsSource = RaCodeGen.GetStringForMember("o", member.Name, mapping.TypeDesc);
}
ilg.Ldarg(0);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ArgBuilder argO = ilg.GetArg("o");
ilg.Ldarg(argO);
ilg.ConvertValue(argO.ArgType, typeof(object));
ilg.Ldc(false);
if (xmlnsSource == null)
ilg.Load(null);
else
{
System.Diagnostics.Debug.Assert(xmlnsSource.StartsWith("o.@", StringComparison.Ordinal));
ILGenLoad(xmlnsSource);
}
MethodInfo XmlSerializationWriter_WriteStartElement = typeof(XmlSerializationWriter).GetMethod(
"WriteStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool), typeof(XmlSerializerNamespaces) }
)!;
ilg.Call(XmlSerializationWriter_WriteStartElement);
if (!mapping.TypeDesc.IsRoot)
{
ilg.If(ilg.GetArg("needType"), Cmp.EqualTo, true);
{
MethodInfo XmlSerializationWriter_WriteXsiType = typeof(XmlSerializationWriter).GetMethod(
"WriteXsiType",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.Call(XmlSerializationWriter_WriteXsiType);
}
ilg.EndIf();
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
if (m.Attribute != null)
{
CodeIdentifier.CheckValidIdentifier(m.Name);
if (m.CheckShouldPersist)
{
ilg.LdargAddress(oArg);
ilg.Call(m.CheckShouldPersistMethodInfo!);
ilg.If();
}
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string memberGet = RaCodeGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc);
ILGenLoad(memberGet);
ilg.If();
}
WriteMember(RaCodeGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc!, "o");
if (m.CheckSpecified != SpecifiedAccessor.None)
{
ilg.EndIf();
}
if (m.CheckShouldPersist)
{
ilg.EndIf();
}
}
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
if (m.Xmlns != null)
continue;
CodeIdentifier.CheckValidIdentifier(m.Name);
bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null);
if (checkShouldPersist)
{
ilg.LdargAddress(oArg);
ilg.Call(m.CheckShouldPersistMethodInfo!);
ilg.If();
}
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string memberGet = RaCodeGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc);
ILGenLoad(memberGet);
ilg.If();
}
string? choiceSource = null;
if (m.ChoiceIdentifier != null)
{
CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName);
choiceSource = RaCodeGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc);
}
WriteMember(RaCodeGen.GetSourceForMember("o", m, m.MemberInfo, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true);
if (m.CheckSpecified != SpecifiedAccessor.None)
{
ilg.EndIf();
}
if (checkShouldPersist)
{
ilg.EndIf();
}
}
WriteEndElement("o");
}
ilg.EndMethod();
}
private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc)
{
// check to see if we can write values of the attribute sequentially
// currently we have only one data type (XmlQualifiedName) that we can not write "inline",
// because we need to output xmlns:qx="..." for each of the qnames
return (listElementTypeDesc != null && listElementTypeDesc != QnameTypeDesc);
}
[RequiresUnreferencedCode("calls WriteAttribute")]
private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDesc memberTypeDesc, string parent)
{
if (memberTypeDesc.IsAbstract) return;
if (memberTypeDesc.IsArrayLike)
{
string aVar = $"a{memberTypeDesc.Name}";
string aiVar = $"ai{memberTypeDesc.Name}";
string iVar = "i";
string fullTypeName = memberTypeDesc.CSharpName;
ilg.EnterScope();
WriteArrayLocalDecl(fullTypeName, aVar, source, memberTypeDesc);
if (memberTypeDesc.IsNullable)
{
ilg.Ldloc(memberTypeDesc.Type!, aVar);
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
}
if (attribute.IsList)
{
if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc))
{
string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteStartAttribute = typeof(XmlWriter).GetMethod(
"WriteStartAttribute",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Load(null);
ilg.Ldstr(GetCSharpString(attribute.Name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Call(XmlWriter_WriteStartAttribute);
}
else
{
LocalBuilder sbLoc = ilg.DeclareOrGetLocal(typeof(StringBuilder), "sb");
ConstructorInfo StringBuilder_ctor = typeof(StringBuilder).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.New(StringBuilder_ctor);
ilg.Stloc(sbLoc);
}
}
TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc!;
if (memberTypeDesc.IsEnumerable)
{
throw Globals.NotSupported("Also fail in IEnumerable member with XmlAttributeAttribute");
}
else
{
LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), iVar);
ilg.For(localI, 0, ilg.GetLocal(aVar));
WriteLocalDecl(aiVar, RaCodeGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type!);
}
if (attribute.IsList)
{
string methodName;
Type methodType;
Type argType;
// check to see if we can write values of the attribute sequentially
if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc))
{
ilg.Ldloc(iVar);
ilg.Ldc(0);
ilg.If(Cmp.NotEqualTo);
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod(
"WriteString",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Ldstr(" ");
ilg.Call(XmlWriter_WriteString);
ilg.EndIf();
ilg.Ldarg(0);
methodName = "WriteValue";
methodType = typeof(XmlSerializationWriter);
}
else
{
MethodInfo StringBuilder_Append = typeof(StringBuilder).GetMethod(
"Append",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string) }
)!;
ilg.Ldloc(iVar);
ilg.Ldc(0);
ilg.If(Cmp.NotEqualTo);
ilg.Ldloc("sb");
ilg.Ldstr(" ");
ilg.Call(StringBuilder_Append);
ilg.Pop();
ilg.EndIf();
ilg.Ldloc("sb");
methodName = "Append";
methodType = typeof(StringBuilder);
}
if (attribute.Mapping is EnumMapping)
WriteEnumValue((EnumMapping)attribute.Mapping, new SourceInfo(aiVar, aiVar, null, arrayElementTypeDesc.Type, ilg), out argType);
else
WritePrimitiveValue(arrayElementTypeDesc, new SourceInfo(aiVar, aiVar, null, arrayElementTypeDesc.Type, ilg), out argType);
MethodInfo method = methodType.GetMethod(
methodName,
CodeGenerator.InstanceBindingFlags,
new Type[] { argType }
)!;
ilg.Call(method);
if (method.ReturnType != typeof(void))
ilg.Pop();
}
else
{
WriteAttribute(new SourceInfo(aiVar, aiVar, null, null, ilg), attribute, parent);
}
if (memberTypeDesc.IsEnumerable)
throw Globals.NotSupported("Also fail in whidbey IEnumerable member with XmlAttributeAttribute");
else
ilg.EndFor();
if (attribute.IsList)
{
// check to see if we can write values of the attribute sequentially
if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc))
{
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteEndAttribute = typeof(XmlWriter).GetMethod(
"WriteEndAttribute",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(XmlWriter_WriteEndAttribute);
}
else
{
MethodInfo StringBuilder_get_Length = typeof(StringBuilder).GetMethod(
"get_Length",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldloc("sb");
ilg.Call(StringBuilder_get_Length);
ilg.Ldc(0);
ilg.If(Cmp.NotEqualTo);
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(attribute.Name));
argTypes.Add(typeof(string));
string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
if (ns != null)
{
ilg.Ldstr(GetCSharpString(ns));
argTypes.Add(typeof(string));
}
MethodInfo Object_ToString = typeof(object).GetMethod(
"ToString",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldloc("sb");
ilg.Call(Object_ToString);
argTypes.Add(typeof(string));
MethodInfo XmlSerializationWriter_WriteAttribute = typeof(XmlSerializationWriter).GetMethod(
"WriteAttribute",
CodeGenerator.InstanceBindingFlags,
argTypes.ToArray()
)!;
ilg.Call(XmlSerializationWriter_WriteAttribute);
ilg.EndIf();
}
}
if (memberTypeDesc.IsNullable)
{
ilg.EndIf();
}
ilg.ExitScope();
}
else
{
WriteAttribute(source, attribute, parent);
}
}
[RequiresUnreferencedCode("calls WritePrimitive")]
private void WriteAttribute(SourceInfo source, AttributeAccessor attribute, string parent)
{
if (attribute.Mapping is SpecialMapping)
{
SpecialMapping special = (SpecialMapping)attribute.Mapping;
if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue)
{
System.Diagnostics.Debug.Assert(parent == "o" || parent == "p");
MethodInfo XmlSerializationWriter_WriteXmlAttribute = typeof(XmlSerializationWriter).GetMethod(
"WriteXmlAttribute",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(XmlNode), typeof(object) }
)!;
ilg.Ldarg(0);
ilg.Ldloc(source.Source);
ilg.Ldarg(parent);
ilg.ConvertValue(ilg.GetArg(parent).ArgType, typeof(object));
ilg.Call(XmlSerializationWriter_WriteXmlAttribute);
}
else
throw new InvalidOperationException(SR.XmlInternalError);
}
else
{
TypeDesc typeDesc = attribute.Mapping!.TypeDesc!;
source = source.CastTo(typeDesc);
WritePrimitive("WriteAttribute", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "", GetConvertedDefaultValue(source.Type, attribute.Default), source, attribute.Mapping, false, false, false);
}
}
private static object? GetConvertedDefaultValue(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
Type? targetType,
object? rawDefaultValue)
{
if (targetType == null)
{
return rawDefaultValue;
}
object? convertedDefaultValue;
if (!targetType.TryConvertTo(rawDefaultValue, out convertedDefaultValue))
{
return rawDefaultValue;
}
return convertedDefaultValue;
}
[RequiresUnreferencedCode("Calls WriteElements")]
private void WriteMember(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors)
{
if (memberTypeDesc.IsArrayLike &&
!(elements.Length == 1 && elements[0].Mapping is ArrayMapping))
WriteArray(source, choiceSource, elements, text, choice, memberTypeDesc);
else
// NOTE: Use different variable name to work around reuse same variable name in different scope
WriteElements(source, choiceSource, elements, text, choice, $"a{memberTypeDesc.Name}", writeAccessors, memberTypeDesc.IsNullable);
}
[RequiresUnreferencedCode("calls WriteArrayItems")]
private void WriteArray(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc)
{
if (elements.Length == 0 && text == null) return;
string arrayTypeName = arrayTypeDesc.CSharpName;
string aName = $"a{arrayTypeDesc.Name}";
ilg.EnterScope();
WriteArrayLocalDecl(arrayTypeName, aName, source, arrayTypeDesc);
LocalBuilder aLoc = ilg.GetLocal(aName);
if (arrayTypeDesc.IsNullable)
{
ilg.Ldloc(aLoc);
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
}
string? cName = null;
if (choice != null)
{
string choiceFullName = choice.Mapping!.TypeDesc!.CSharpName;
SourceInfo choiceSourceInfo = new SourceInfo(choiceSource!, null, choice.MemberInfo, null, ilg);
cName = $"c{choice.Mapping.TypeDesc.Name}";
WriteArrayLocalDecl($"{choiceFullName}[]", cName, choiceSourceInfo, choice.Mapping.TypeDesc);
// write check for the choice identifier array
Label labelEnd = ilg.DefineLabel();
Label labelTrue = ilg.DefineLabel();
LocalBuilder cLoc = ilg.GetLocal(cName);
ilg.Ldloc(cLoc);
ilg.Load(null);
ilg.Beq(labelTrue);
ilg.Ldloc(cLoc);
ilg.Ldlen();
ilg.Ldloc(aLoc);
ilg.Ldlen();
ilg.Clt();
ilg.Br(labelEnd);
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
ilg.MarkLabel(labelEnd);
ilg.If();
MethodInfo XmlSerializationWriter_CreateInvalidChoiceIdentifierValueException = typeof(XmlSerializationWriter).GetMethod(
"CreateInvalidChoiceIdentifierValueException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(choice.Mapping.TypeDesc.FullName));
ilg.Ldstr(GetCSharpString(choice.MemberName));
ilg.Call(XmlSerializationWriter_CreateInvalidChoiceIdentifierValueException);
ilg.Throw();
ilg.EndIf();
}
WriteArrayItems(elements, text, choice, arrayTypeDesc, aName, cName!);
if (arrayTypeDesc.IsNullable)
{
ilg.EndIf();
}
ilg.ExitScope();
}
[RequiresUnreferencedCode("calls WriteElements")]
private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc, string arrayName, string? choiceName)
{
TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc!;
if (arrayTypeDesc.IsEnumerable)
{
LocalBuilder eLoc = ilg.DeclareLocal(typeof(IEnumerator), "e");
ilg.LoadAddress(ilg.GetVariable(arrayName));
MethodInfo getEnumeratorMethod;
if (arrayTypeDesc.IsPrivateImplementation)
{
Type typeIEnumerable = typeof(IEnumerable);
getEnumeratorMethod = typeIEnumerable.GetMethod(
"GetEnumerator",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable);
}
else if (arrayTypeDesc.IsGenericInterface)
{
Type typeIEnumerable = typeof(IEnumerable<>).MakeGenericType(arrayElementTypeDesc.Type!);
getEnumeratorMethod = typeIEnumerable.GetMethod(
"GetEnumerator",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable);
}
else
{
getEnumeratorMethod = arrayTypeDesc.Type!.GetMethod(
"GetEnumerator",
Type.EmptyTypes)!;
}
ilg.Call(getEnumeratorMethod);
ilg.ConvertValue(getEnumeratorMethod.ReturnType, typeof(IEnumerator));
ilg.Stloc(eLoc);
ilg.Ldloc(eLoc);
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
ilg.WhileBegin();
string arrayNamePlusA = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}a{arrayElementTypeDesc.Name}";
string arrayNamePlusI = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}i{arrayElementTypeDesc.Name}";
WriteLocalDecl(arrayNamePlusI, "e.Current", arrayElementTypeDesc.Type!);
WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), $"{choiceName}i", elements, text, choice, arrayNamePlusA, true, true);
ilg.WhileBeginCondition(); // while (e.MoveNext())
MethodInfo IEnumerator_MoveNext = typeof(IEnumerator).GetMethod(
"MoveNext",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.Ldloc(eLoc);
ilg.Call(IEnumerator_MoveNext);
ilg.WhileEndCondition();
ilg.WhileEnd();
ilg.EndIf(); // if (e != null)
}
else
{
// Filter out type specific for index (code match reusing local).
string iPlusArrayName = $"i{(arrayName).Replace(arrayTypeDesc.Name, "")}";
string arrayNamePlusA = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}a{arrayElementTypeDesc.Name}";
string arrayNamePlusI = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}i{arrayElementTypeDesc.Name}";
LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), iPlusArrayName);
ilg.For(localI, 0, ilg.GetLocal(arrayName));
int count = elements.Length + (text == null ? 0 : 1);
if (count > 1)
{
WriteLocalDecl(arrayNamePlusI, RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type!);
if (choice != null)
{
WriteLocalDecl($"{choiceName}i", RaCodeGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping!.TypeDesc!), choice.Mapping.TypeDesc!.Type!);
}
WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), $"{choiceName}i", elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable);
}
else
{
WriteElements(new SourceInfo(RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), null, null, arrayElementTypeDesc.Type, ilg), null, elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable);
}
ilg.EndFor();
}
}
[RequiresUnreferencedCode("Calls WriteElement")]
private void WriteElements(SourceInfo source, string? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable)
{
if (elements.Length == 0 && text == null) return;
if (elements.Length == 1 && text == null)
{
TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping!.TypeDesc!.CreateArrayTypeDesc() : elements[0].Mapping!.TypeDesc!;
if (!elements[0].Any && !elements[0].Mapping!.TypeDesc!.IsOptionalValue)
source = source.CastTo(td);
WriteElement(source, elements[0], arrayName, writeAccessors);
}
else
{
bool doEndIf = false;
if (isNullable && choice == null)
{
source.Load(typeof(object));
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
doEndIf = true;
}
int anyCount = 0;
var namedAnys = new List<ElementAccessor>();
ElementAccessor? unnamedAny = null; // can only have one
bool wroteFirstIf = false;
string? enumTypeName = choice == null ? null : choice.Mapping!.TypeDesc!.FullName;
for (int i = 0; i < elements.Length; i++)
{
ElementAccessor element = elements[i];
if (element.Any)
{
anyCount++;
if (element.Name != null && element.Name.Length > 0)
namedAnys.Add(element);
else if (unnamedAny == null)
unnamedAny = element;
}
else if (choice != null)
{
string fullTypeName = element.Mapping!.TypeDesc!.CSharpName;
object? enumValue;
string enumFullName = $"{enumTypeName}.@{FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue)}";
if (wroteFirstIf) ilg.InitElseIf();
else { wroteFirstIf = true; ilg.InitIf(); }
ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type);
ilg.Load(enumValue);
ilg.Ceq();
if (isNullable && !element.IsNullable)
{
Label labelFalse = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
ilg.Brfalse(labelFalse);
source.Load(typeof(object));
ilg.Load(null);
ilg.Cne();
ilg.Br_S(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
}
ilg.AndIf();
WriteChoiceTypeCheck(source, fullTypeName, choice!, enumFullName, element.Mapping.TypeDesc);
SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc);
WriteElement(element.Any ? source : castedSource, element, arrayName, writeAccessors);
}
else
{
TypeDesc td = element.IsUnbounded ? element.Mapping!.TypeDesc!.CreateArrayTypeDesc() : element.Mapping!.TypeDesc!;
if (wroteFirstIf) ilg.InitElseIf();
else { wroteFirstIf = true; ilg.InitIf(); }
WriteInstanceOf(source, td.Type!);
// WriteInstanceOf leave bool on the stack
ilg.AndIf();
SourceInfo castedSource = source.CastTo(td);
WriteElement(element.Any ? source : castedSource, element, arrayName, writeAccessors);
}
}
if (wroteFirstIf)
{
if (anyCount > 0)
{
// See "else " below
if (elements.Length - anyCount > 0)
{ // NOOP
}
else ilg.EndIf();
}
}
if (anyCount > 0)
{
if (elements.Length - anyCount > 0) ilg.InitElseIf();
else ilg.InitIf();
source.Load(typeof(object));
ilg.IsInst(typeof(XmlElement));
ilg.Load(null);
ilg.Cne();
ilg.AndIf();
LocalBuilder elemLoc = ilg.DeclareLocal(typeof(XmlElement), "elem");
source.Load(typeof(XmlElement));
ilg.Stloc(elemLoc);
int c = 0;
foreach (ElementAccessor element in namedAnys)
{
if (c++ > 0) ilg.InitElseIf();
else ilg.InitIf();
string? enumFullName = null;
Label labelEnd, labelFalse;
if (choice != null)
{
object? enumValue;
enumFullName = $"{enumTypeName}.@{FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue)}";
labelFalse = ilg.DefineLabel();
labelEnd = ilg.DefineLabel();
ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type);
ilg.Load(enumValue);
ilg.Bne(labelFalse);
if (isNullable && !element.IsNullable)
{
source.Load(typeof(object));
ilg.Load(null);
ilg.Cne();
}
else
{
ilg.Ldc(true);
}
ilg.Br(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
ilg.AndIf();
}
labelFalse = ilg.DefineLabel();
labelEnd = ilg.DefineLabel();
MethodInfo XmlNode_get_Name = typeof(XmlNode).GetMethod(
"get_Name",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod(
"get_NamespaceURI",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_Name);
ilg.Ldstr(GetCSharpString(element.Name));
MethodInfo String_op_Equality = typeof(string).GetMethod(
"op_Equality",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Call(String_op_Equality);
ilg.Brfalse(labelFalse);
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_NamespaceURI);
ilg.Ldstr(GetCSharpString(element.Namespace));
ilg.Call(String_op_Equality);
ilg.Br(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
if (choice != null) ilg.If();
else ilg.AndIf();
WriteElement(new SourceInfo("elem", null, null, elemLoc.LocalType, ilg), element, arrayName, writeAccessors);
if (choice != null)
{
ilg.Else();
MethodInfo XmlSerializationWriter_CreateChoiceIdentifierValueException = typeof(XmlSerializationWriter).GetMethod(
"CreateChoiceIdentifierValueException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(enumFullName));
ilg.Ldstr(GetCSharpString(choice.MemberName));
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_Name);
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_NamespaceURI);
ilg.Call(XmlSerializationWriter_CreateChoiceIdentifierValueException);
ilg.Throw();
ilg.EndIf();
}
}
if (c > 0)
{
ilg.Else();
}
if (unnamedAny != null)
{
WriteElement(new SourceInfo("elem", null, null, elemLoc.LocalType, ilg), unnamedAny, arrayName, writeAccessors);
}
else
{
MethodInfo XmlSerializationWriter_CreateUnknownAnyElementException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownAnyElementException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldloc(elemLoc);
MethodInfo XmlNode_get_Name = typeof(XmlNode).GetMethod(
"get_Name",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod(
"get_NamespaceURI",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Call(XmlNode_get_Name);
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_NamespaceURI);
ilg.Call(XmlSerializationWriter_CreateUnknownAnyElementException);
ilg.Throw();
}
if (c > 0)
{
ilg.EndIf();
}
}
if (text != null)
{
if (elements.Length > 0)
{
ilg.InitElseIf();
WriteInstanceOf(source, text.Mapping!.TypeDesc!.Type!);
ilg.AndIf();
SourceInfo castedSource = source.CastTo(text.Mapping.TypeDesc);
WriteText(castedSource, text);
}
else
{
SourceInfo castedSource = source.CastTo(text.Mapping!.TypeDesc!);
WriteText(castedSource, text);
}
}
if (elements.Length > 0)
{
if (isNullable)
{
ilg.InitElseIf();
source.Load(null);
ilg.Load(null);
ilg.AndIf(Cmp.NotEqualTo);
}
else
{
ilg.Else();
}
MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) })!;
ilg.Ldarg(0);
source.Load(typeof(object));
ilg.Call(XmlSerializationWriter_CreateUnknownTypeException);
ilg.Throw();
ilg.EndIf();
}
// See ilg.If() cond above
if (doEndIf) // if (isNullable && choice == null)
ilg.EndIf();
}
}
[RequiresUnreferencedCode("calls Load")]
private void WriteText(SourceInfo source, TextAccessor text)
{
if (text.Mapping is PrimitiveMapping)
{
PrimitiveMapping mapping = (PrimitiveMapping)text.Mapping;
Type argType;
ilg.Ldarg(0);
if (text.Mapping is EnumMapping)
{
WriteEnumValue((EnumMapping)text.Mapping, source, out argType);
}
else
{
WritePrimitiveValue(mapping.TypeDesc!, source, out argType);
}
MethodInfo XmlSerializationWriter_WriteValue = typeof(XmlSerializationWriter).GetMethod(
"WriteValue",
CodeGenerator.InstanceBindingFlags,
new Type[] { argType }
)!;
ilg.Call(XmlSerializationWriter_WriteValue);
}
else if (text.Mapping is SpecialMapping)
{
SpecialMapping mapping = (SpecialMapping)text.Mapping;
switch (mapping.TypeDesc!.Kind)
{
case TypeKind.Node:
MethodInfo WriteTo = source.Type!.GetMethod(
"WriteTo",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(XmlWriter) }
)!;
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
source.Load(source.Type);
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(WriteTo);
break;
default:
throw new InvalidOperationException(SR.XmlInternalError);
}
}
}
[RequiresUnreferencedCode("Calls WriteCheckDefault")]
private void WriteElement(SourceInfo source, ElementAccessor element, string arrayName, bool writeAccessor)
{
string name = writeAccessor ? element.Name : element.Mapping!.TypeName!;
string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : "");
if (element.Mapping is NullableMapping)
{
if (source.Type == element.Mapping.TypeDesc!.Type)
{
MethodInfo Nullable_get_HasValue = element.Mapping.TypeDesc.Type!.GetMethod(
"get_HasValue",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
source.LoadAddress(element.Mapping.TypeDesc.Type);
ilg.Call(Nullable_get_HasValue);
}
else
{
source.Load(null);
ilg.Load(null);
ilg.Cne();
}
ilg.If();
SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc.BaseTypeDesc!);
ElementAccessor e = element.Clone();
e.Mapping = ((NullableMapping)element.Mapping).BaseMapping;
WriteElement(e.Any ? source : castedSource, e, arrayName, writeAccessor);
if (element.IsNullable)
{
ilg.Else();
WriteLiteralNullTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : "");
}
ilg.EndIf();
}
else if (element.Mapping is ArrayMapping)
{
ArrayMapping mapping = (ArrayMapping)element.Mapping;
if (element.IsUnbounded)
{
throw Globals.NotSupported("Unreachable: IsUnbounded is never set true!");
}
else
{
ilg.EnterScope();
string fullTypeName = mapping.TypeDesc!.CSharpName;
WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc);
if (element.IsNullable)
{
WriteNullCheckBegin(arrayName, element);
}
else
{
if (mapping.TypeDesc.IsNullable)
{
ilg.Ldloc(ilg.GetLocal(arrayName));
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
}
}
WriteStartElement(name, ns, false);
WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null);
WriteEndElement();
if (element.IsNullable)
{
ilg.EndIf();
}
else
{
if (mapping.TypeDesc.IsNullable)
{
ilg.EndIf();
}
}
ilg.ExitScope();
}
}
else if (element.Mapping is EnumMapping)
{
WritePrimitive("WriteElementString", name, ns, element.Default, source, element.Mapping, false, true, element.IsNullable);
}
else if (element.Mapping is PrimitiveMapping)
{
PrimitiveMapping mapping = (PrimitiveMapping)element.Mapping;
if (mapping.TypeDesc == QnameTypeDesc)
WriteQualifiedNameElement(name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, element.IsNullable, mapping);
else
{
string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : "";
WritePrimitive(element.IsNullable ? ("WriteNullableStringLiteral" + suffixRaw) : ("WriteElementString" + suffixRaw),
name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, mapping, false, true, element.IsNullable);
}
}
else if (element.Mapping is StructMapping)
{
StructMapping mapping = (StructMapping)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
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
argTypes.Add(typeof(string));
ilg.Ldstr(GetCSharpString(ns));
argTypes.Add(typeof(string));
source.Load(mapping.TypeDesc!.Type);
argTypes.Add(mapping.TypeDesc.Type!);
if (mapping.TypeDesc.IsNullable)
{
ilg.Ldc(element.IsNullable);
argTypes.Add(typeof(bool));
}
ilg.Ldc(false);
argTypes.Add(typeof(bool));
MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(void),
argTypes.ToArray());
ilg.Call(methodBuilder);
}
else if (element.Mapping is SpecialMapping)
{
if (element.Mapping is SerializableMapping)
{
WriteElementCall("WriteSerializable", typeof(IXmlSerializable), source, name, ns, element.IsNullable, !element.Any);
}
else
{
// XmlNode, XmlElement
Label ifLabel1 = ilg.DefineLabel();
Label ifLabel2 = ilg.DefineLabel();
source.Load(null);
ilg.IsInst(typeof(XmlNode));
ilg.Brtrue(ifLabel1);
source.Load(null);
ilg.Load(null);
ilg.Ceq();
ilg.Br(ifLabel2);
ilg.MarkLabel(ifLabel1);
ilg.Ldc(true);
ilg.MarkLabel(ifLabel2);
ilg.If();
WriteElementCall("WriteElementLiteral", typeof(XmlNode), source, name, ns, element.IsNullable, element.Any);
ilg.Else();
MethodInfo XmlSerializationWriter_CreateInvalidAnyTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateInvalidAnyTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
)!;
ilg.Ldarg(0);
source.Load(null);
ilg.Call(XmlSerializationWriter_CreateInvalidAnyTypeException);
ilg.Throw();
ilg.EndIf();
}
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
[RequiresUnreferencedCode("XmlSerializationWriter methods have RequiresUnreferencedCode")]
private void WriteElementCall(string func, Type cast, SourceInfo source, string? name, string? ns, bool isNullable, bool isAny)
{
MethodInfo XmlSerializationWriter_func = typeof(XmlSerializationWriter).GetMethod(
func,
CodeGenerator.InstanceBindingFlags,
new Type[] { cast, typeof(string), typeof(string), typeof(bool), typeof(bool) }
)!;
ilg.Ldarg(0);
source.Load(cast);
ilg.Ldstr(GetCSharpString(name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Ldc(isNullable);
ilg.Ldc(isAny);
ilg.Call(XmlSerializationWriter_func);
}
[RequiresUnreferencedCode("Dynamically looks for '!=' operator on 'value' parameter")]
private void WriteCheckDefault(SourceInfo source, object value, bool isNullable)
{
if (value is string && ((string)value).Length == 0)
{
// special case for string compare
Label labelEnd = ilg.DefineLabel();
Label labelFalse = ilg.DefineLabel();
Label labelTrue = ilg.DefineLabel();
source.Load(typeof(string));
if (isNullable)
// check == null with false
ilg.Brfalse(labelTrue);
else
//check != null with false
ilg.Brfalse(labelFalse);
MethodInfo String_get_Length = typeof(string).GetMethod(
"get_Length",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
source.Load(typeof(string));
ilg.Call(String_get_Length);
ilg.Ldc(0);
ilg.Cne();
ilg.Br(labelEnd);
if (isNullable)
{
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
}
else
{
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
}
ilg.MarkLabel(labelEnd);
ilg.If();
}
else
{
if (value == null)
{
source.Load(typeof(object));
ilg.Load(null);
ilg.Cne();
}
else if (value.GetType().IsPrimitive)
{
source.Load(null);
ilg.Ldc(Convert.ChangeType(value, source.Type!, CultureInfo.InvariantCulture));
ilg.Cne();
}
else
{
Type valueType = value.GetType();
source.Load(valueType);
ilg.Ldc(value is string ? GetCSharpString((string)value) : value);
MethodInfo op_Inequality = valueType.GetMethod(
"op_Inequality",
CodeGenerator.StaticBindingFlags,
new Type[] { valueType, valueType }
)!;
if (op_Inequality != null)
ilg.Call(op_Inequality);
else
ilg.Cne();
}
ilg.If();
}
}
[RequiresUnreferencedCode("calls Load")]
private void WriteChoiceTypeCheck(SourceInfo source, string fullTypeName, ChoiceIdentifierAccessor choice, string enumName, TypeDesc typeDesc)
{
Label labelFalse = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
source.Load(typeof(object));
ilg.Load(null);
ilg.Beq(labelFalse);
WriteInstanceOf(source, typeDesc.Type!);
// Negative
ilg.Ldc(false);
ilg.Ceq();
ilg.Br(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
ilg.If();
MethodInfo XmlSerializationWriter_CreateMismatchChoiceException = typeof(XmlSerializationWriter).GetMethod(
"CreateMismatchChoiceException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(typeDesc.FullName));
ilg.Ldstr(GetCSharpString(choice.MemberName));
ilg.Ldstr(GetCSharpString(enumName));
ilg.Call(XmlSerializationWriter_CreateMismatchChoiceException);
ilg.Throw();
ilg.EndIf();
}
[RequiresUnreferencedCode("calls WriteLiteralNullTag")]
private void WriteNullCheckBegin(string source, ElementAccessor element)
{
LocalBuilder local = ilg.GetLocal(source);
Debug.Assert(!local.LocalType.IsValueType);
ilg.Load(local);
ilg.Load(null);
ilg.If(Cmp.EqualTo);
WriteLiteralNullTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : "");
ilg.Else();
}
[RequiresUnreferencedCode("calls ILGenLoad")]
private void WriteNamespaces(string source)
{
MethodInfo XmlSerializationWriter_WriteNamespaceDeclarations = typeof(XmlSerializationWriter).GetMethod(
"WriteNamespaceDeclarations",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(XmlSerializerNamespaces) }
)!;
ilg.Ldarg(0);
ILGenLoad(source, typeof(XmlSerializerNamespaces));
ilg.Call(XmlSerializationWriter_WriteNamespaceDeclarations);
}
private int FindXmlnsIndex(MemberMapping[] members)
{
for (int i = 0; i < members.Length; i++)
{
if (members[i].Xmlns == null)
continue;
return i;
}
return -1;
}
[RequiresUnreferencedCode("calls WriteLocalDecl")]
private void WriteLocalDecl(string variableName, string initValue, Type type)
{
RaCodeGen.WriteLocalDecl(variableName, new SourceInfo(initValue, initValue, null, type, ilg));
}
[RequiresUnreferencedCode("calls WriteArrayLocalDecl")]
private void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc)
{
RaCodeGen.WriteArrayLocalDecl(typeName, variableName, initValue, arrayTypeDesc);
}
private void WriteTypeCompare(string variable, Type type)
{
RaCodeGen.WriteTypeCompare(variable, type, ilg);
}
[RequiresUnreferencedCode("calls WriteInstanceOf")]
private void WriteInstanceOf(SourceInfo source, Type type)
{
RaCodeGen.WriteInstanceOf(source, type, ilg);
}
private void WriteArrayTypeCompare(string variable, Type arrayType)
{
RaCodeGen.WriteArrayTypeCompare(variable, arrayType, ilg);
}
private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object? eValue)
{
string? enumValue = null;
eValue = null;
for (int i = 0; i < choiceMapping.Constants!.Length; i++)
{
string xmlName = choiceMapping.Constants[i].XmlName;
if (element.Any && element.Name.Length == 0)
{
if (xmlName == "##any:")
{
enumValue = choiceMapping.Constants[i].Name;
eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value);
break;
}
continue;
}
int colon = xmlName.LastIndexOf(':');
string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon);
string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1);
if (element.Name == choiceName)
{
if ((element.Form == XmlSchemaForm.Unqualified && string.IsNullOrEmpty(choiceNs)) || element.Namespace == choiceNs)
{
enumValue = choiceMapping.Constants[i].Name;
eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value);
break;
}
}
}
if (enumValue == null || enumValue.Length == 0)
{
if (element.Any && element.Name.Length == 0)
{
// Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute.
throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc!.FullName));
}
// Type {0} is missing value for '{1}'.
throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc!.FullName, $"{element.Namespace}:{element.Name}", element.Name, element.Namespace));
}
CodeIdentifier.CheckValidIdentifier(enumValue);
return enumValue;
}
}
internal sealed class ReflectionAwareILGen
{
// reflectionVariables holds mapping between a reflection entity
// referenced in the generated code (such as TypeInfo,
// FieldInfo) and the variable which represent the entity (and
// initialized before).
// The types of reflection entity and corresponding key is
// given below.
// ----------------------------------------------------------------------------------
// Entity Key
// ----------------------------------------------------------------------------------
// Assembly assembly.FullName
// Type CodeIdentifier.EscapedKeywords(type.FullName)
// Field fieldName+":"+CodeIdentifier.EscapedKeywords(containingType.FullName>)
// Property propertyName+":"+CodeIdentifier.EscapedKeywords(containingType.FullName)
// ArrayAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(Array).FullName)
// MyCollectionAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(MyCollection).FullName)
// ----------------------------------------------------------------------------------
internal ReflectionAwareILGen() { }
[RequiresUnreferencedCode("calls GetTypeDesc")]
internal void WriteReflectionInit(TypeScope scope)
{
foreach (Type type in scope.Types)
{
scope.GetTypeDesc(type);
}
}
internal void ILGenForEnumLongValue(CodeGenerator ilg, string variable)
{
ArgBuilder argV = ilg.GetArg(variable);
ilg.Ldarg(argV);
ilg.ConvertValue(argV.ArgType, typeof(long));
}
internal string GetStringForTypeof(string typeFullName)
{
{
return $"typeof({typeFullName})";
}
}
internal string GetStringForMember(string obj, string memberName, TypeDesc typeDesc)
{
return $"{obj}.@{memberName}";
}
internal SourceInfo GetSourceForMember(string obj, MemberMapping member, TypeDesc typeDesc, CodeGenerator ilg)
{
return GetSourceForMember(obj, member, member.MemberInfo, typeDesc, ilg);
}
internal SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, TypeDesc typeDesc, CodeGenerator ilg)
{
return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc!.Type, ilg);
}
internal void ILGenForEnumMember(CodeGenerator ilg, Type type, string memberName)
{
ilg.Ldc(Enum.Parse(type, memberName, false));
}
internal string GetStringForArrayMember(string? arrayName, string subscript, TypeDesc arrayTypeDesc)
{
{
return $"{arrayName}[{subscript}]";
}
}
internal string GetStringForMethod(string obj, string typeFullName, string memberName)
{
return $"{obj}.{memberName}(";
}
[RequiresUnreferencedCode("calls ILGenForCreateInstance")]
internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInaccessible, bool cast)
{
if (!ctorInaccessible)
{
ConstructorInfo ctor = type.GetConstructor(
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
if (ctor != null)
ilg.New(ctor);
else
{
Debug.Assert(type.IsValueType);
LocalBuilder tmpLoc = ilg.GetTempLocal(type);
ilg.Ldloca(tmpLoc);
ilg.InitObj(type);
ilg.Ldloc(tmpLoc);
}
return;
}
ILGenForCreateInstance(ilg, type, cast ? type : null, ctorInaccessible);
}
[RequiresUnreferencedCode("calls GetType")]
internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, bool nonPublic)
{
// Special case DBNull
if (type == typeof(DBNull))
{
FieldInfo DBNull_Value = type.GetField("Value", CodeGenerator.StaticBindingFlags)!;
ilg.LoadMember(DBNull_Value);
return;
}
// Special case XElement
// codegen the same as 'internal XElement : this("default") { }'
if (type.FullName == "System.Xml.Linq.XElement")
{
Type? xName = type.Assembly.GetType("System.Xml.Linq.XName");
if (xName != null)
{
MethodInfo XName_op_Implicit = xName.GetMethod(
"op_Implicit",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(string) }
)!;
ConstructorInfo XElement_ctor = type.GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { xName }
)!;
if (XName_op_Implicit != null && XElement_ctor != null)
{
ilg.Ldstr("default");
ilg.Call(XName_op_Implicit);
ilg.New(XElement_ctor);
return;
}
}
}
Label labelReturn = ilg.DefineLabel();
Label labelEndIf = ilg.DefineLabel();
// TypeInfo typeInfo = type.GetTypeInfo();
// typeInfo not declared explicitly
ilg.Ldc(type);
MethodInfo getTypeInfoMehod = typeof(IntrospectionExtensions).GetMethod(
"GetTypeInfo",
CodeGenerator.StaticBindingFlags,
new[] { typeof(Type) }
)!;
ilg.Call(getTypeInfoMehod);
// IEnumerator<ConstructorInfo> e = typeInfo.DeclaredConstructors.GetEnumerator();
LocalBuilder enumerator = ilg.DeclareLocal(typeof(IEnumerator<>).MakeGenericType(typeof(ConstructorInfo)), "e");
MethodInfo getDeclaredConstructors = typeof(TypeInfo).GetMethod("get_DeclaredConstructors")!;
MethodInfo getEnumerator = typeof(IEnumerable<>).MakeGenericType(typeof(ConstructorInfo)).GetMethod("GetEnumerator")!;
ilg.Call(getDeclaredConstructors);
ilg.Call(getEnumerator);
ilg.Stloc(enumerator);
ilg.WhileBegin();
// ConstructorInfo constructorInfo = e.Current();
MethodInfo enumeratorCurrent = typeof(IEnumerator).GetMethod("get_Current")!;
ilg.Ldloc(enumerator);
ilg.Call(enumeratorCurrent);
LocalBuilder constructorInfo = ilg.DeclareLocal(typeof(ConstructorInfo), "constructorInfo");
ilg.Stloc(constructorInfo);
// if (!constructorInfo.IsStatic && constructorInfo.GetParameters.Length() == 0)
ilg.Ldloc(constructorInfo);
MethodInfo constructorIsStatic = typeof(ConstructorInfo).GetMethod("get_IsStatic")!;
ilg.Call(constructorIsStatic);
ilg.Brtrue(labelEndIf);
ilg.Ldloc(constructorInfo);
MethodInfo constructorGetParameters = typeof(ConstructorInfo).GetMethod("GetParameters")!;
ilg.Call(constructorGetParameters);
ilg.Ldlen();
ilg.Ldc(0);
ilg.Cne();
ilg.Brtrue(labelEndIf);
// constructorInfo.Invoke(null);
MethodInfo constructorInvoke = typeof(ConstructorInfo).GetMethod("Invoke", new Type[] { typeof(object[]) })!;
ilg.Ldloc(constructorInfo);
ilg.Load(null);
ilg.Call(constructorInvoke);
ilg.Br(labelReturn);
ilg.MarkLabel(labelEndIf);
ilg.WhileBeginCondition(); // while (e.MoveNext())
MethodInfo IEnumeratorMoveNext = typeof(IEnumerator).GetMethod(
"MoveNext",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.Ldloc(enumerator);
ilg.Call(IEnumeratorMoveNext);
ilg.WhileEndCondition();
ilg.WhileEnd();
MethodInfo Activator_CreateInstance = typeof(Activator).GetMethod(
"CreateInstance",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(Type) }
)!;
ilg.Ldc(type);
ilg.Call(Activator_CreateInstance);
ilg.MarkLabel(labelReturn);
if (cast != null)
ilg.ConvertValue(Activator_CreateInstance.ReturnType, cast);
}
[RequiresUnreferencedCode("calls LoadMember")]
internal void WriteLocalDecl(string variableName, SourceInfo initValue)
{
Type localType = initValue.Type!;
LocalBuilder localA = initValue.ILG.DeclareOrGetLocal(localType, variableName);
if (initValue.Source != null)
{
if (initValue == "null")
{
initValue.ILG.Load(null);
}
else
{
if (initValue.Arg.StartsWith("o.@", StringComparison.Ordinal))
{
Debug.Assert(initValue.MemberInfo != null);
Debug.Assert(initValue.MemberInfo.Name == initValue.Arg.Substring(3));
initValue.ILG.LoadMember(initValue.ILG.GetLocal("o"), initValue.MemberInfo);
}
else if (initValue.Source.EndsWith(']'))
{
initValue.Load(initValue.Type);
}
else if (initValue.Source == "fixup.Source" || initValue.Source == "e.Current")
{
string[] vars = initValue.Source.Split('.');
object fixup = initValue.ILG.GetVariable(vars[0]);
PropertyInfo propInfo = initValue.ILG.GetVariableType(fixup).GetProperty(vars[1])!;
initValue.ILG.LoadMember(fixup, propInfo);
initValue.ILG.ConvertValue(propInfo.PropertyType, localA.LocalType);
}
else
{
object sVar = initValue.ILG.GetVariable(initValue.Arg);
initValue.ILG.Load(sVar);
initValue.ILG.ConvertValue(initValue.ILG.GetVariableType(sVar), localA.LocalType);
}
}
initValue.ILG.Stloc(localA);
}
}
[RequiresUnreferencedCode("calls ILGenForCreateInstance")]
internal void WriteCreateInstance(string source, bool ctorInaccessible, Type type, CodeGenerator ilg)
{
LocalBuilder sLoc = ilg.DeclareOrGetLocal(type, source);
ILGenForCreateInstance(ilg, type, ctorInaccessible, ctorInaccessible);
ilg.Stloc(sLoc);
}
[RequiresUnreferencedCode("calls Load")]
internal void WriteInstanceOf(SourceInfo source, Type type, CodeGenerator ilg)
{
{
source.Load(typeof(object));
ilg.IsInst(type);
ilg.Load(null);
ilg.Cne();
return;
}
}
[RequiresUnreferencedCode("calls Load")]
internal void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc)
{
Debug.Assert(typeName == arrayTypeDesc.CSharpName || typeName == $"{arrayTypeDesc.CSharpName}[]");
Type localType = (typeName == arrayTypeDesc.CSharpName) ? arrayTypeDesc.Type! : arrayTypeDesc.Type!.MakeArrayType();
// This may need reused variable to get code compat?
LocalBuilder local = initValue.ILG.DeclareOrGetLocal(localType, variableName);
if (initValue != null)
{
initValue.Load(local.LocalType);
initValue.ILG.Stloc(local);
}
}
internal void WriteTypeCompare(string variable, Type type, CodeGenerator ilg)
{
Debug.Assert(type != null);
Debug.Assert(ilg != null);
ilg.Ldloc(typeof(Type), variable);
ilg.Ldc(type);
ilg.Ceq();
}
internal void WriteArrayTypeCompare(string variable, Type arrayType, CodeGenerator ilg)
{
{
Debug.Assert(arrayType != null);
Debug.Assert(ilg != null);
ilg.Ldloc(typeof(Type), variable);
ilg.Ldc(arrayType);
ilg.Ceq();
return;
}
}
[return: NotNullIfNotNull("value")]
internal static string? GetQuotedCSharpString(string? value)
{
if (value == null)
{
return null;
}
StringBuilder writer = new StringBuilder();
writer.Append("@\"");
writer.Append(GetCSharpString(value));
writer.Append('"');
return writer.ToString();
}
[return: NotNullIfNotNull("value")]
internal static string? GetCSharpString(string? value)
{
if (value == null)
{
return null;
}
StringBuilder writer = new StringBuilder();
foreach (char ch in value)
{
if (ch < 32)
{
if (ch == '\r')
writer.Append("\\r");
else if (ch == '\n')
writer.Append("\\n");
else if (ch == '\t')
writer.Append("\\t");
else
{
byte b = (byte)ch;
writer.Append("\\x");
writer.Append(HexConverter.ToCharUpper(b >> 4));
writer.Append(HexConverter.ToCharUpper(b));
}
}
else if (ch == '\"')
{
writer.Append("\"\"");
}
else
{
writer.Append(ch);
}
}
return writer.ToString();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Xml.Schema;
using System.Xml.Extensions;
using System.Diagnostics.CodeAnalysis;
namespace System.Xml.Serialization
{
internal sealed class XmlSerializationWriterILGen : XmlSerializationILGen
{
[RequiresUnreferencedCode("creates XmlSerializationILGen")]
internal XmlSerializationWriterILGen(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(XmlSerializationWriter),
Type.EmptyTypes);
foreach (TypeScope scope in Scopes)
{
foreach (TypeMapping mapping in scope.TypeMappings)
{
if (mapping is StructMapping || mapping is EnumMapping)
{
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);
}
}
[RequiresUnreferencedCode("calls GenerateReferencedMethods")]
internal Type GenerateEnd()
{
GenerateReferencedMethods();
GenerateInitCallbacksMethod();
this.typeBuilder.DefineDefaultConstructor(
CodeGenerator.PublicMethodAttributes);
return this.typeBuilder.CreateTypeInfo()!.AsType();
}
[RequiresUnreferencedCode("calls GenerateTypeElement")]
internal string? GenerateElement(XmlMapping xmlMapping)
{
if (!xmlMapping.IsWriteable)
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));
}
private void GenerateInitCallbacksMethod()
{
ilg = new CodeGenerator(this.typeBuilder);
ilg.BeginMethod(typeof(void), "InitCallbacks", Type.EmptyTypes, Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.EndMethod();
}
[RequiresUnreferencedCode("calls Load")]
private void WriteQualifiedNameElement(string name, string? ns, object? defaultValue, SourceInfo source, bool nullable, TypeMapping mapping)
{
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value;
if (hasDefault)
{
throw Globals.NotSupported("XmlQualifiedName DefaultValue not supported. Fail in WriteValue()");
}
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
argTypes.Add(typeof(string));
if (ns != null)
{
ilg.Ldstr(GetCSharpString(ns));
argTypes.Add(typeof(string));
}
source.Load(mapping.TypeDesc!.Type!);
argTypes.Add(mapping.TypeDesc.Type!);
MethodInfo XmlSerializationWriter_WriteXXX = typeof(XmlSerializationWriter).GetMethod(
nullable ? ("WriteNullableQualifiedNameLiteral") : "WriteElementQualifiedName",
CodeGenerator.InstanceBindingFlags,
argTypes.ToArray()
)!;
ilg.Call(XmlSerializationWriter_WriteXXX);
}
[RequiresUnreferencedCode("calls Load")]
private void WriteEnumValue(EnumMapping mapping, SourceInfo source, out Type returnType)
{
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
// For enum, its write method (eg. Write1_Gender) could be called multiple times
// prior to its declaration.
MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(string),
new Type[] { mapping.TypeDesc!.Type! });
ilg.Ldarg(0);
source.Load(mapping.TypeDesc.Type!);
ilg.Call(methodBuilder);
returnType = typeof(string);
}
[RequiresUnreferencedCode("calls Load")]
private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type returnType)
{
if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String")
{
source.Load(typeDesc.Type!);
returnType = typeDesc.Type!;
}
else
{
if (!typeDesc.HasCustomFormatter)
{
Type argType = typeDesc.Type!;
// No ToString(Byte), compiler used ToString(Int16) instead.
if (argType == typeof(byte))
argType = typeof(short);
// No ToString(UInt16), compiler used ToString(Int32) instead.
else if (argType == typeof(ushort))
argType = typeof(int);
MethodInfo XmlConvert_ToString = typeof(XmlConvert).GetMethod(
"ToString",
CodeGenerator.StaticBindingFlags,
new Type[] { argType }
)!;
source.Load(typeDesc.Type!);
ilg.Call(XmlConvert_ToString);
returnType = XmlConvert_ToString.ReturnType;
}
else
{
// Only these methods below that is non Static and need to ldarg("this") for Call.
BindingFlags bindingFlags = CodeGenerator.StaticBindingFlags;
if (typeDesc.FormatterName == "XmlQualifiedName")
{
bindingFlags = CodeGenerator.InstanceBindingFlags;
ilg.Ldarg(0);
}
MethodInfo FromXXX = typeof(XmlSerializationWriter).GetMethod(
$"From{typeDesc.FormatterName}",
bindingFlags,
new Type[] { typeDesc.Type! }
)!;
source.Load(typeDesc.Type!);
ilg.Call(FromXXX);
returnType = FromXXX.ReturnType;
}
}
}
[RequiresUnreferencedCode("Calls WriteCheckDefault")]
private void WritePrimitive(string method, string name, string? ns, object? defaultValue, SourceInfo source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable)
{
TypeDesc typeDesc = mapping.TypeDesc!;
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport;
if (hasDefault)
{
if (mapping is EnumMapping)
{
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (defaultValue!.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name));
#endif
source.Load(mapping.TypeDesc!.Type!);
string? enumDefaultValue = null;
if (((EnumMapping)mapping).IsFlags)
{
string[] values = ((string)defaultValue!).Split(null);
for (int i = 0; i < values.Length; i++)
{
if (values[i] == null || values[i].Length == 0)
continue;
if (i > 0)
enumDefaultValue += ", ";
enumDefaultValue += values[i];
}
}
else
{
enumDefaultValue = (string)defaultValue!;
}
ilg.Ldc(Enum.Parse(mapping.TypeDesc.Type!, enumDefaultValue!, false));
ilg.If(Cmp.NotEqualTo); // " != "
}
else
{
WriteCheckDefault(source, defaultValue!, isNullable);
}
}
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
argTypes.Add(typeof(string));
ilg.Ldstr(GetCSharpString(name));
if (ns != null)
{
argTypes.Add(typeof(string));
ilg.Ldstr(GetCSharpString(ns));
}
Type argType;
if (mapping is EnumMapping)
{
WriteEnumValue((EnumMapping)mapping, source, out argType);
argTypes.Add(argType);
}
else
{
WritePrimitiveValue(typeDesc, source, out argType);
argTypes.Add(argType);
}
if (writeXsiType)
{
argTypes.Add(typeof(XmlQualifiedName));
ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.New(XmlQualifiedName_ctor);
}
MethodInfo XmlSerializationWriter_method = typeof(XmlSerializationWriter).GetMethod(
method,
CodeGenerator.InstanceBindingFlags,
argTypes.ToArray()
)!;
ilg.Call(XmlSerializationWriter_method);
if (hasDefault)
{
ilg.EndIf();
}
}
[RequiresUnreferencedCode("XmlSerializationWriter methods have RequiresUnreferencedCode")]
private void WriteTag(string methodName, string name, string? ns)
{
MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod(
methodName,
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Call(XmlSerializationWriter_Method);
}
[RequiresUnreferencedCode("XmlSerializationWriter methods have RequiresUnreferencedCode")]
private void WriteTag(string methodName, string name, string? ns, bool writePrefixed)
{
MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod(
methodName,
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Load(null);
ilg.Ldc(writePrefixed);
ilg.Call(XmlSerializationWriter_Method);
}
[RequiresUnreferencedCode("calls WriteTag")]
private void WriteStartElement(string name, string? ns, bool writePrefixed)
{
WriteTag("WriteStartElement", name, ns, writePrefixed);
}
private void WriteEndElement()
{
MethodInfo XmlSerializationWriter_WriteEndElement = typeof(XmlSerializationWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_WriteEndElement);
}
private void WriteEndElement(string source)
{
MethodInfo XmlSerializationWriter_WriteEndElement = typeof(XmlSerializationWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
)!;
object oVar = ilg.GetVariable(source);
ilg.Ldarg(0);
ilg.Load(oVar);
ilg.ConvertValue(ilg.GetVariableType(oVar), typeof(object));
ilg.Call(XmlSerializationWriter_WriteEndElement);
}
[RequiresUnreferencedCode("calls WriteTag")]
private void WriteLiteralNullTag(string name, string? ns)
{
WriteTag("WriteNullTagLiteral", name, ns);
}
[RequiresUnreferencedCode("calls WriteTag")]
private void WriteEmptyTag(string name, string? ns)
{
WriteTag("WriteEmptyTag", name, ns);
}
[RequiresUnreferencedCode("calls WriteMember")]
private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping)
{
ElementAccessor element = xmlMembersMapping.Accessor;
MembersMapping mapping = (MembersMapping)element.Mapping!;
bool hasWrapperElement = mapping.HasWrapperElement;
bool writeAccessors = mapping.WriteAccessors;
string methodName = NextMethodName(element.Name);
ilg = new CodeGenerator(this.typeBuilder);
ilg.BeginMethod(
typeof(void),
methodName,
new Type[] { typeof(object[]) },
new string[] { "p" },
CodeGenerator.PublicMethodAttributes
);
MethodInfo XmlSerializationWriter_WriteStartDocument = typeof(XmlSerializationWriter).GetMethod(
"WriteStartDocument",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_WriteStartDocument);
MethodInfo XmlSerializationWriter_TopLevelElement = typeof(XmlSerializationWriter).GetMethod(
"TopLevelElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_TopLevelElement);
// in the top-level method add check for the parameters length,
// because visual basic does not have a concept of an <out> parameter it uses <ByRef> instead
// so sometime we think that we have more parameters then supplied
LocalBuilder pLengthLoc = ilg.DeclareLocal(typeof(int), "pLength");
ilg.Ldarg("p");
ilg.Ldlen();
ilg.Stloc(pLengthLoc);
if (hasWrapperElement)
{
WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""), false);
int xmlnsMember = FindXmlnsIndex(mapping.Members!);
if (xmlnsMember >= 0)
{
string source = string.Create(CultureInfo.InvariantCulture, $"(({typeof(XmlSerializerNamespaces).FullName})p[{xmlnsMember}])");
ilg.Ldloc(pLengthLoc);
ilg.Ldc(xmlnsMember);
ilg.If(Cmp.GreaterThan);
WriteNamespaces(source);
ilg.EndIf();
}
for (int i = 0; i < mapping.Members!.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Attribute != null && !member.Ignore)
{
SourceInfo source = new SourceInfo($"p[{i}]", null, null, pLengthLoc.LocalType.GetElementType()!, ilg);
SourceInfo? specifiedSource = null;
int specifiedPosition = 0;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = $"{member.Name}Specified";
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = new SourceInfo($"((bool)p[{j}])", null, null, typeof(bool), ilg);
specifiedPosition = j;
break;
}
}
}
ilg.Ldloc(pLengthLoc);
ilg.Ldc(i);
ilg.If(Cmp.GreaterThan);
if (specifiedSource != null)
{
Label labelTrue = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
ilg.Ldloc(pLengthLoc);
ilg.Ldc(specifiedPosition);
ilg.Ble(labelTrue);
specifiedSource.Load(typeof(bool));
ilg.Br_S(labelEnd);
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
ilg.MarkLabel(labelEnd);
ilg.If();
}
WriteMember(source, member.Attribute, member.TypeDesc!, "p");
if (specifiedSource != null)
{
ilg.EndIf();
}
ilg.EndIf();
}
}
}
for (int i = 0; i < mapping.Members!.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Xmlns != null)
continue;
if (member.Ignore)
continue;
SourceInfo? specifiedSource = null;
int specifiedPosition = 0;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = $"{member.Name}Specified";
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = new SourceInfo($"((bool)p[{j}])", null, null, typeof(bool), ilg);
specifiedPosition = j;
break;
}
}
}
ilg.Ldloc(pLengthLoc);
ilg.Ldc(i);
ilg.If(Cmp.GreaterThan);
if (specifiedSource != null)
{
Label labelTrue = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
ilg.Ldloc(pLengthLoc);
ilg.Ldc(specifiedPosition);
ilg.Ble(labelTrue);
specifiedSource.Load(typeof(bool));
ilg.Br_S(labelEnd);
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
ilg.MarkLabel(labelEnd);
ilg.If();
}
string source = $"p[{i}]";
string? enumSource = null;
if (member.ChoiceIdentifier != null)
{
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName)
{
enumSource = $"(({mapping.Members[j].TypeDesc!.CSharpName})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 (enumSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Can not find " + member.ChoiceIdentifier.MemberName + " in the members mapping."));
#endif
}
// override writeAccessors choice when we've written a wrapper element
WriteMember(new SourceInfo(source, source, null, null, ilg), enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement);
if (specifiedSource != null)
{
ilg.EndIf();
}
ilg.EndIf();
}
if (hasWrapperElement)
{
WriteEndElement();
}
ilg.EndMethod();
return methodName;
}
[RequiresUnreferencedCode("calls WriteMember")]
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(void),
methodName,
new Type[] { typeof(object) },
new string[] { "o" },
CodeGenerator.PublicMethodAttributes
);
MethodInfo XmlSerializationWriter_WriteStartDocument = typeof(XmlSerializationWriter).GetMethod(
"WriteStartDocument",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_WriteStartDocument);
ilg.If(ilg.GetArg("o"), Cmp.EqualTo, null);
if (element.IsNullable)
{
WriteLiteralNullTag(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""));
}
else
WriteEmptyTag(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""));
ilg.GotoMethodEnd();
ilg.EndIf();
if (!mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive)
{
MethodInfo XmlSerializationWriter_TopLevelElement = typeof(XmlSerializationWriter).GetMethod(
"TopLevelElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_TopLevelElement);
}
WriteMember(new SourceInfo("o", "o", null, typeof(object), ilg), null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, true);
ilg.EndMethod();
return methodName;
}
private string NextMethodName(string name)
{
return string.Create(CultureInfo.InvariantCulture, $"Write{++NextMethodNumber}_{CodeIdentifier.MakeValidInternal(name)}");
}
private void WriteEnumMethod(EnumMapping mapping)
{
string? methodName;
MethodNames.TryGetValue(mapping, out methodName);
List<Type> argTypes = new List<Type>();
List<string> argNames = new List<string>();
argTypes.Add(mapping.TypeDesc!.Type!);
argNames.Add("v");
ilg = new CodeGenerator(this.typeBuilder);
ilg.BeginMethod(
typeof(string),
GetMethodBuilder(methodName!),
argTypes.ToArray(),
argNames.ToArray(),
CodeGenerator.PrivateMethodAttributes);
LocalBuilder sLoc = ilg.DeclareLocal(typeof(string), "s");
ilg.Load(null);
ilg.Stloc(sLoc);
ConstantMapping[] constants = mapping.Constants!;
if (constants.Length > 0)
{
var values = new HashSet<long>();
List<Label> caseLabels = new List<Label>();
List<string> retValues = new List<string>();
Label defaultLabel = ilg.DefineLabel();
Label endSwitchLabel = ilg.DefineLabel();
// This local is necessary; otherwise, it becomes if/else
LocalBuilder localTmp = ilg.DeclareLocal(mapping.TypeDesc.Type!, "localTmp");
ilg.Ldarg("v");
ilg.Stloc(localTmp);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
if (values.Add(c.Value))
{
Label caseLabel = ilg.DefineLabel();
ilg.Ldloc(localTmp);
ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type!, c.Value));
ilg.Beq(caseLabel);
caseLabels.Add(caseLabel);
retValues.Add(GetCSharpString(c.XmlName));
}
}
if (mapping.IsFlags)
{
ilg.Br(defaultLabel);
for (int i = 0; i < caseLabels.Count; i++)
{
ilg.MarkLabel(caseLabels[i]);
ilg.Ldc(retValues[i]);
ilg.Stloc(sLoc);
ilg.Br(endSwitchLabel);
}
ilg.MarkLabel(defaultLabel);
RaCodeGen.ILGenForEnumLongValue(ilg, "v");
LocalBuilder strArray = ilg.DeclareLocal(typeof(string[]), "strArray");
ilg.NewArray(typeof(string), constants.Length);
ilg.Stloc(strArray);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
ilg.Ldloc(strArray);
ilg.Ldc(i);
ilg.Ldstr(GetCSharpString(c.XmlName));
ilg.Stelem(typeof(string));
}
ilg.Ldloc(strArray);
LocalBuilder longArray = ilg.DeclareLocal(typeof(long[]), "longArray");
ilg.NewArray(typeof(long), constants.Length);
ilg.Stloc(longArray);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
ilg.Ldloc(longArray);
ilg.Ldc(i);
ilg.Ldc(c.Value);
ilg.Stelem(typeof(long));
}
ilg.Ldloc(longArray);
ilg.Ldstr(GetCSharpString(mapping.TypeDesc.FullName));
MethodInfo XmlSerializationWriter_FromEnum = typeof(XmlSerializationWriter).GetMethod(
"FromEnum",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(long), typeof(string[]), typeof(long[]), typeof(string) }
)!;
ilg.Call(XmlSerializationWriter_FromEnum);
ilg.Stloc(sLoc);
ilg.Br(endSwitchLabel);
}
else
{
ilg.Br(defaultLabel);
// Case bodies
for (int i = 0; i < caseLabels.Count; i++)
{
ilg.MarkLabel(caseLabels[i]);
ilg.Ldc(retValues[i]);
ilg.Stloc(sLoc);
ilg.Br(endSwitchLabel);
}
MethodInfo CultureInfo_get_InvariantCulture = typeof(CultureInfo).GetMethod(
"get_InvariantCulture",
CodeGenerator.StaticBindingFlags,
Type.EmptyTypes
)!;
MethodInfo Int64_ToString = typeof(long).GetMethod(
"ToString",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(IFormatProvider) }
)!;
MethodInfo XmlSerializationWriter_CreateInvalidEnumValueException = typeof(XmlSerializationWriter).GetMethod(
"CreateInvalidEnumValueException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object), typeof(string) }
)!;
// Default body
ilg.MarkLabel(defaultLabel);
ilg.Ldarg(0);
ilg.Ldarg("v");
ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long));
LocalBuilder numLoc = ilg.DeclareLocal(typeof(long), "num");
ilg.Stloc(numLoc);
// Invoke method on Value type need address
ilg.LdlocAddress(numLoc);
ilg.Call(CultureInfo_get_InvariantCulture);
ilg.Call(Int64_ToString);
ilg.Ldstr(GetCSharpString(mapping.TypeDesc.FullName));
ilg.Call(XmlSerializationWriter_CreateInvalidEnumValueException);
ilg.Throw();
}
ilg.MarkLabel(endSwitchLabel);
}
ilg.Ldloc(sLoc);
ilg.EndMethod();
}
private void WriteDerivedTypes(StructMapping mapping)
{
for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
ilg.InitElseIf();
WriteTypeCompare("t", derived.TypeDesc!.Type!);
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("derived from " + mapping.TypeDesc!.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name));
#endif
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
argTypes.Add(typeof(string));
ilg.Ldarg("n");
argTypes.Add(typeof(string));
ilg.Ldarg("ns");
object oVar = ilg.GetVariable("o");
Type oType = ilg.GetVariableType(oVar);
ilg.Load(oVar);
ilg.ConvertValue(oType, derived.TypeDesc.Type!);
argTypes.Add(derived.TypeDesc.Type!);
if (derived.TypeDesc.IsNullable)
{
argTypes.Add(typeof(bool));
ilg.Ldarg("isNullable");
}
argTypes.Add(typeof(bool));
ilg.Ldc(true);
MethodInfo methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(void),
argTypes.ToArray());
ilg.Call(methodBuilder);
ilg.GotoMethodEnd();
WriteDerivedTypes(derived);
}
}
[RequiresUnreferencedCode("calls WriteMember")]
private void WriteEnumAndArrayTypes()
{
foreach (TypeScope scope in Scopes)
{
foreach (Mapping m in scope.TypeMappings)
{
if (m is EnumMapping)
{
EnumMapping mapping = (EnumMapping)m;
ilg.InitElseIf();
WriteTypeCompare("t", mapping.TypeDesc!.Type!);
// WriteXXXTypeCompare leave bool on the stack
ilg.AndIf();
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
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod(
"WriteStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Call(XmlWriter_WriteStartElement);
MethodInfo XmlSerializationWriter_WriteXsiType = typeof(XmlSerializationWriter).GetMethod(
"WriteXsiType",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.Call(XmlSerializationWriter_WriteXsiType);
MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(string),
new Type[] { mapping.TypeDesc.Type! }
);
MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod(
"WriteString",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
object oVar = ilg.GetVariable("o");
ilg.Ldarg(0);
ilg.Load(oVar);
ilg.ConvertValue(ilg.GetVariableType(oVar), mapping.TypeDesc.Type!);
ilg.Call(methodBuilder);
ilg.Call(XmlWriter_WriteString);
MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(XmlWriter_WriteEndElement);
ilg.GotoMethodEnd();
}
else if (m is ArrayMapping)
{
ArrayMapping? mapping = m as ArrayMapping;
if (mapping == null) continue;
ilg.InitElseIf();
if (mapping.TypeDesc!.IsArray)
WriteArrayTypeCompare("t", mapping.TypeDesc.Type!);
else
WriteTypeCompare("t", mapping.TypeDesc.Type!);
// WriteXXXTypeCompare leave bool on the stack
ilg.AndIf();
ilg.EnterScope();
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod(
"WriteStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Call(XmlWriter_WriteStartElement);
MethodInfo XmlSerializationWriter_WriteXsiType = typeof(XmlSerializationWriter).GetMethod(
"WriteXsiType",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.Call(XmlSerializationWriter_WriteXsiType);
WriteMember(new SourceInfo("o", "o", null, null, ilg), null, mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, true);
MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod(
"WriteEndElement",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(XmlWriter_WriteEndElement);
ilg.GotoMethodEnd();
ilg.ExitScope();
}
}
}
}
[RequiresUnreferencedCode("Calls WriteMember")]
private void WriteStructMethod(StructMapping mapping)
{
string? methodName;
MethodNames.TryGetValue(mapping, out methodName);
ilg = new CodeGenerator(this.typeBuilder);
List<Type> argTypes = new List<Type>(5);
List<string> argNames = new List<string>(5);
argTypes.Add(typeof(string));
argNames.Add("n");
argTypes.Add(typeof(string));
argNames.Add("ns");
argTypes.Add(mapping.TypeDesc!.Type!);
argNames.Add("o");
if (mapping.TypeDesc.IsNullable)
{
argTypes.Add(typeof(bool));
argNames.Add("isNullable");
}
argTypes.Add(typeof(bool));
argNames.Add("needType");
ilg.BeginMethod(typeof(void),
GetMethodBuilder(methodName!),
argTypes.ToArray(),
argNames.ToArray(),
CodeGenerator.PrivateMethodAttributes);
if (mapping.TypeDesc.IsNullable)
{
ilg.If(ilg.GetArg("o"), Cmp.EqualTo, null);
{
ilg.If(ilg.GetArg("isNullable"), Cmp.EqualTo, true);
{
MethodInfo XmlSerializationWriter_WriteNullTagLiteral = typeof(XmlSerializationWriter).GetMethod(
"WriteNullTagLiteral",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Call(XmlSerializationWriter_WriteNullTagLiteral);
}
ilg.EndIf();
ilg.GotoMethodEnd();
}
ilg.EndIf();
}
ilg.If(ilg.GetArg("needType"), Cmp.NotEqualTo, true); // if (!needType)
LocalBuilder tLoc = ilg.DeclareLocal(typeof(Type), "t");
MethodInfo Object_GetType = typeof(object).GetMethod(
"GetType",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ArgBuilder oArg = ilg.GetArg("o");
ilg.LdargAddress(oArg);
ilg.ConvertAddress(oArg.ArgType, typeof(object));
ilg.Call(Object_GetType);
ilg.Stloc(tLoc);
WriteTypeCompare("t", mapping.TypeDesc.Type!);
// Bool on the stack from WriteTypeCompare.
ilg.If(); // if (t == typeof(...))
WriteDerivedTypes(mapping);
if (mapping.TypeDesc.IsRoot)
WriteEnumAndArrayTypes();
ilg.Else();
if (mapping.TypeDesc.IsRoot)
{
MethodInfo XmlSerializationWriter_WriteTypedPrimitive = typeof(XmlSerializationWriter).GetMethod(
"WriteTypedPrimitive",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) }
)!;
ilg.Ldarg(0);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ilg.Ldarg("o");
ilg.Ldc(true);
ilg.Call(XmlSerializationWriter_WriteTypedPrimitive);
ilg.GotoMethodEnd();
}
else
{
MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
)!;
ilg.Ldarg(0);
ilg.Ldarg(oArg);
ilg.ConvertValue(oArg.ArgType, typeof(object));
ilg.Call(XmlSerializationWriter_CreateUnknownTypeException);
ilg.Throw();
}
ilg.EndIf(); // if (t == typeof(...))
ilg.EndIf(); // if (!needType)
if (!mapping.TypeDesc.IsAbstract)
{
if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type))
{
MethodInfo XmlSerializationWriter_set_EscapeName = typeof(XmlSerializationWriter).GetMethod(
"set_EscapeName",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(bool) }
)!;
ilg.Ldarg(0);
ilg.Ldc(false);
ilg.Call(XmlSerializationWriter_set_EscapeName);
}
string? xmlnsSource = null;
MemberMapping[] members = TypeScope.GetAllMembers(mapping, memberInfos);
int xmlnsMember = FindXmlnsIndex(members);
if (xmlnsMember >= 0)
{
MemberMapping member = members[xmlnsMember];
CodeIdentifier.CheckValidIdentifier(member.Name);
xmlnsSource = RaCodeGen.GetStringForMember("o", member.Name, mapping.TypeDesc);
}
ilg.Ldarg(0);
ilg.Ldarg("n");
ilg.Ldarg("ns");
ArgBuilder argO = ilg.GetArg("o");
ilg.Ldarg(argO);
ilg.ConvertValue(argO.ArgType, typeof(object));
ilg.Ldc(false);
if (xmlnsSource == null)
ilg.Load(null);
else
{
System.Diagnostics.Debug.Assert(xmlnsSource.StartsWith("o.@", StringComparison.Ordinal));
ILGenLoad(xmlnsSource);
}
MethodInfo XmlSerializationWriter_WriteStartElement = typeof(XmlSerializationWriter).GetMethod(
"WriteStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool), typeof(XmlSerializerNamespaces) }
)!;
ilg.Call(XmlSerializationWriter_WriteStartElement);
if (!mapping.TypeDesc.IsRoot)
{
ilg.If(ilg.GetArg("needType"), Cmp.EqualTo, true);
{
MethodInfo XmlSerializationWriter_WriteXsiType = typeof(XmlSerializationWriter).GetMethod(
"WriteXsiType",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(mapping.TypeName));
ilg.Ldstr(GetCSharpString(mapping.Namespace));
ilg.Call(XmlSerializationWriter_WriteXsiType);
}
ilg.EndIf();
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
if (m.Attribute != null)
{
CodeIdentifier.CheckValidIdentifier(m.Name);
if (m.CheckShouldPersist)
{
ilg.LdargAddress(oArg);
ilg.Call(m.CheckShouldPersistMethodInfo!);
ilg.If();
}
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string memberGet = RaCodeGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc);
ILGenLoad(memberGet);
ilg.If();
}
WriteMember(RaCodeGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc!, "o");
if (m.CheckSpecified != SpecifiedAccessor.None)
{
ilg.EndIf();
}
if (m.CheckShouldPersist)
{
ilg.EndIf();
}
}
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
if (m.Xmlns != null)
continue;
CodeIdentifier.CheckValidIdentifier(m.Name);
bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null);
if (checkShouldPersist)
{
ilg.LdargAddress(oArg);
ilg.Call(m.CheckShouldPersistMethodInfo!);
ilg.If();
}
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string memberGet = RaCodeGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc);
ILGenLoad(memberGet);
ilg.If();
}
string? choiceSource = null;
if (m.ChoiceIdentifier != null)
{
CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName);
choiceSource = RaCodeGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc);
}
WriteMember(RaCodeGen.GetSourceForMember("o", m, m.MemberInfo, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true);
if (m.CheckSpecified != SpecifiedAccessor.None)
{
ilg.EndIf();
}
if (checkShouldPersist)
{
ilg.EndIf();
}
}
WriteEndElement("o");
}
ilg.EndMethod();
}
private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc)
{
// check to see if we can write values of the attribute sequentially
// currently we have only one data type (XmlQualifiedName) that we can not write "inline",
// because we need to output xmlns:qx="..." for each of the qnames
return (listElementTypeDesc != null && listElementTypeDesc != QnameTypeDesc);
}
[RequiresUnreferencedCode("calls WriteAttribute")]
private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDesc memberTypeDesc, string parent)
{
if (memberTypeDesc.IsAbstract) return;
if (memberTypeDesc.IsArrayLike)
{
string aVar = $"a{memberTypeDesc.Name}";
string aiVar = $"ai{memberTypeDesc.Name}";
string iVar = "i";
string fullTypeName = memberTypeDesc.CSharpName;
ilg.EnterScope();
WriteArrayLocalDecl(fullTypeName, aVar, source, memberTypeDesc);
if (memberTypeDesc.IsNullable)
{
ilg.Ldloc(memberTypeDesc.Type!, aVar);
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
}
if (attribute.IsList)
{
if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc))
{
string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteStartAttribute = typeof(XmlWriter).GetMethod(
"WriteStartAttribute",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Load(null);
ilg.Ldstr(GetCSharpString(attribute.Name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Call(XmlWriter_WriteStartAttribute);
}
else
{
LocalBuilder sbLoc = ilg.DeclareOrGetLocal(typeof(StringBuilder), "sb");
ConstructorInfo StringBuilder_ctor = typeof(StringBuilder).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.New(StringBuilder_ctor);
ilg.Stloc(sbLoc);
}
}
TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc!;
if (memberTypeDesc.IsEnumerable)
{
throw Globals.NotSupported("Also fail in IEnumerable member with XmlAttributeAttribute");
}
else
{
LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), iVar);
ilg.For(localI, 0, ilg.GetLocal(aVar));
WriteLocalDecl(aiVar, RaCodeGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type!);
}
if (attribute.IsList)
{
string methodName;
Type methodType;
Type argType;
// check to see if we can write values of the attribute sequentially
if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc))
{
ilg.Ldloc(iVar);
ilg.Ldc(0);
ilg.If(Cmp.NotEqualTo);
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod(
"WriteString",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Ldstr(" ");
ilg.Call(XmlWriter_WriteString);
ilg.EndIf();
ilg.Ldarg(0);
methodName = "WriteValue";
methodType = typeof(XmlSerializationWriter);
}
else
{
MethodInfo StringBuilder_Append = typeof(StringBuilder).GetMethod(
"Append",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string) }
)!;
ilg.Ldloc(iVar);
ilg.Ldc(0);
ilg.If(Cmp.NotEqualTo);
ilg.Ldloc("sb");
ilg.Ldstr(" ");
ilg.Call(StringBuilder_Append);
ilg.Pop();
ilg.EndIf();
ilg.Ldloc("sb");
methodName = "Append";
methodType = typeof(StringBuilder);
}
if (attribute.Mapping is EnumMapping)
WriteEnumValue((EnumMapping)attribute.Mapping, new SourceInfo(aiVar, aiVar, null, arrayElementTypeDesc.Type, ilg), out argType);
else
WritePrimitiveValue(arrayElementTypeDesc, new SourceInfo(aiVar, aiVar, null, arrayElementTypeDesc.Type, ilg), out argType);
MethodInfo method = methodType.GetMethod(
methodName,
CodeGenerator.InstanceBindingFlags,
new Type[] { argType }
)!;
ilg.Call(method);
if (method.ReturnType != typeof(void))
ilg.Pop();
}
else
{
WriteAttribute(new SourceInfo(aiVar, aiVar, null, null, ilg), attribute, parent);
}
if (memberTypeDesc.IsEnumerable)
throw Globals.NotSupported("Also fail in whidbey IEnumerable member with XmlAttributeAttribute");
else
ilg.EndFor();
if (attribute.IsList)
{
// check to see if we can write values of the attribute sequentially
if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc))
{
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlWriter_WriteEndAttribute = typeof(XmlWriter).GetMethod(
"WriteEndAttribute",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(XmlWriter_WriteEndAttribute);
}
else
{
MethodInfo StringBuilder_get_Length = typeof(StringBuilder).GetMethod(
"get_Length",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldloc("sb");
ilg.Call(StringBuilder_get_Length);
ilg.Ldc(0);
ilg.If(Cmp.NotEqualTo);
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(attribute.Name));
argTypes.Add(typeof(string));
string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
if (ns != null)
{
ilg.Ldstr(GetCSharpString(ns));
argTypes.Add(typeof(string));
}
MethodInfo Object_ToString = typeof(object).GetMethod(
"ToString",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldloc("sb");
ilg.Call(Object_ToString);
argTypes.Add(typeof(string));
MethodInfo XmlSerializationWriter_WriteAttribute = typeof(XmlSerializationWriter).GetMethod(
"WriteAttribute",
CodeGenerator.InstanceBindingFlags,
argTypes.ToArray()
)!;
ilg.Call(XmlSerializationWriter_WriteAttribute);
ilg.EndIf();
}
}
if (memberTypeDesc.IsNullable)
{
ilg.EndIf();
}
ilg.ExitScope();
}
else
{
WriteAttribute(source, attribute, parent);
}
}
[RequiresUnreferencedCode("calls WritePrimitive")]
private void WriteAttribute(SourceInfo source, AttributeAccessor attribute, string parent)
{
if (attribute.Mapping is SpecialMapping)
{
SpecialMapping special = (SpecialMapping)attribute.Mapping;
if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue)
{
System.Diagnostics.Debug.Assert(parent == "o" || parent == "p");
MethodInfo XmlSerializationWriter_WriteXmlAttribute = typeof(XmlSerializationWriter).GetMethod(
"WriteXmlAttribute",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(XmlNode), typeof(object) }
)!;
ilg.Ldarg(0);
ilg.Ldloc(source.Source);
ilg.Ldarg(parent);
ilg.ConvertValue(ilg.GetArg(parent).ArgType, typeof(object));
ilg.Call(XmlSerializationWriter_WriteXmlAttribute);
}
else
throw new InvalidOperationException(SR.XmlInternalError);
}
else
{
TypeDesc typeDesc = attribute.Mapping!.TypeDesc!;
source = source.CastTo(typeDesc);
WritePrimitive("WriteAttribute", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "", GetConvertedDefaultValue(source.Type, attribute.Default), source, attribute.Mapping, false, false, false);
}
}
private static object? GetConvertedDefaultValue(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
Type? targetType,
object? rawDefaultValue)
{
if (targetType == null)
{
return rawDefaultValue;
}
object? convertedDefaultValue;
if (!targetType.TryConvertTo(rawDefaultValue, out convertedDefaultValue))
{
return rawDefaultValue;
}
return convertedDefaultValue;
}
[RequiresUnreferencedCode("Calls WriteElements")]
private void WriteMember(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors)
{
if (memberTypeDesc.IsArrayLike &&
!(elements.Length == 1 && elements[0].Mapping is ArrayMapping))
WriteArray(source, choiceSource, elements, text, choice, memberTypeDesc);
else
// NOTE: Use different variable name to work around reuse same variable name in different scope
WriteElements(source, choiceSource, elements, text, choice, $"a{memberTypeDesc.Name}", writeAccessors, memberTypeDesc.IsNullable);
}
[RequiresUnreferencedCode("calls WriteArrayItems")]
private void WriteArray(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc)
{
if (elements.Length == 0 && text == null) return;
string arrayTypeName = arrayTypeDesc.CSharpName;
string aName = $"a{arrayTypeDesc.Name}";
ilg.EnterScope();
WriteArrayLocalDecl(arrayTypeName, aName, source, arrayTypeDesc);
LocalBuilder aLoc = ilg.GetLocal(aName);
if (arrayTypeDesc.IsNullable)
{
ilg.Ldloc(aLoc);
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
}
string? cName = null;
if (choice != null)
{
string choiceFullName = choice.Mapping!.TypeDesc!.CSharpName;
SourceInfo choiceSourceInfo = new SourceInfo(choiceSource!, null, choice.MemberInfo, null, ilg);
cName = $"c{choice.Mapping.TypeDesc.Name}";
WriteArrayLocalDecl($"{choiceFullName}[]", cName, choiceSourceInfo, choice.Mapping.TypeDesc);
// write check for the choice identifier array
Label labelEnd = ilg.DefineLabel();
Label labelTrue = ilg.DefineLabel();
LocalBuilder cLoc = ilg.GetLocal(cName);
ilg.Ldloc(cLoc);
ilg.Load(null);
ilg.Beq(labelTrue);
ilg.Ldloc(cLoc);
ilg.Ldlen();
ilg.Ldloc(aLoc);
ilg.Ldlen();
ilg.Clt();
ilg.Br(labelEnd);
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
ilg.MarkLabel(labelEnd);
ilg.If();
MethodInfo XmlSerializationWriter_CreateInvalidChoiceIdentifierValueException = typeof(XmlSerializationWriter).GetMethod(
"CreateInvalidChoiceIdentifierValueException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(choice.Mapping.TypeDesc.FullName));
ilg.Ldstr(GetCSharpString(choice.MemberName));
ilg.Call(XmlSerializationWriter_CreateInvalidChoiceIdentifierValueException);
ilg.Throw();
ilg.EndIf();
}
WriteArrayItems(elements, text, choice, arrayTypeDesc, aName, cName!);
if (arrayTypeDesc.IsNullable)
{
ilg.EndIf();
}
ilg.ExitScope();
}
[RequiresUnreferencedCode("calls WriteElements")]
private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc, string arrayName, string? choiceName)
{
TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc!;
if (arrayTypeDesc.IsEnumerable)
{
LocalBuilder eLoc = ilg.DeclareLocal(typeof(IEnumerator), "e");
ilg.LoadAddress(ilg.GetVariable(arrayName));
MethodInfo getEnumeratorMethod;
if (arrayTypeDesc.IsPrivateImplementation)
{
Type typeIEnumerable = typeof(IEnumerable);
getEnumeratorMethod = typeIEnumerable.GetMethod(
"GetEnumerator",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable);
}
else if (arrayTypeDesc.IsGenericInterface)
{
Type typeIEnumerable = typeof(IEnumerable<>).MakeGenericType(arrayElementTypeDesc.Type!);
getEnumeratorMethod = typeIEnumerable.GetMethod(
"GetEnumerator",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable);
}
else
{
getEnumeratorMethod = arrayTypeDesc.Type!.GetMethod(
"GetEnumerator",
Type.EmptyTypes)!;
}
ilg.Call(getEnumeratorMethod);
ilg.ConvertValue(getEnumeratorMethod.ReturnType, typeof(IEnumerator));
ilg.Stloc(eLoc);
ilg.Ldloc(eLoc);
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
ilg.WhileBegin();
string arrayNamePlusA = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}a{arrayElementTypeDesc.Name}";
string arrayNamePlusI = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}i{arrayElementTypeDesc.Name}";
WriteLocalDecl(arrayNamePlusI, "e.Current", arrayElementTypeDesc.Type!);
WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), $"{choiceName}i", elements, text, choice, arrayNamePlusA, true, true);
ilg.WhileBeginCondition(); // while (e.MoveNext())
MethodInfo IEnumerator_MoveNext = typeof(IEnumerator).GetMethod(
"MoveNext",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.Ldloc(eLoc);
ilg.Call(IEnumerator_MoveNext);
ilg.WhileEndCondition();
ilg.WhileEnd();
ilg.EndIf(); // if (e != null)
}
else
{
// Filter out type specific for index (code match reusing local).
string iPlusArrayName = $"i{(arrayName).Replace(arrayTypeDesc.Name, "")}";
string arrayNamePlusA = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}a{arrayElementTypeDesc.Name}";
string arrayNamePlusI = $"{(arrayName).Replace(arrayTypeDesc.Name, "")}i{arrayElementTypeDesc.Name}";
LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), iPlusArrayName);
ilg.For(localI, 0, ilg.GetLocal(arrayName));
int count = elements.Length + (text == null ? 0 : 1);
if (count > 1)
{
WriteLocalDecl(arrayNamePlusI, RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type!);
if (choice != null)
{
WriteLocalDecl($"{choiceName}i", RaCodeGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping!.TypeDesc!), choice.Mapping.TypeDesc!.Type!);
}
WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), $"{choiceName}i", elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable);
}
else
{
WriteElements(new SourceInfo(RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), null, null, arrayElementTypeDesc.Type, ilg), null, elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable);
}
ilg.EndFor();
}
}
[RequiresUnreferencedCode("Calls WriteElement")]
private void WriteElements(SourceInfo source, string? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable)
{
if (elements.Length == 0 && text == null) return;
if (elements.Length == 1 && text == null)
{
TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping!.TypeDesc!.CreateArrayTypeDesc() : elements[0].Mapping!.TypeDesc!;
if (!elements[0].Any && !elements[0].Mapping!.TypeDesc!.IsOptionalValue)
source = source.CastTo(td);
WriteElement(source, elements[0], arrayName, writeAccessors);
}
else
{
bool doEndIf = false;
if (isNullable && choice == null)
{
source.Load(typeof(object));
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
doEndIf = true;
}
int anyCount = 0;
var namedAnys = new List<ElementAccessor>();
ElementAccessor? unnamedAny = null; // can only have one
bool wroteFirstIf = false;
string? enumTypeName = choice == null ? null : choice.Mapping!.TypeDesc!.FullName;
for (int i = 0; i < elements.Length; i++)
{
ElementAccessor element = elements[i];
if (element.Any)
{
anyCount++;
if (element.Name != null && element.Name.Length > 0)
namedAnys.Add(element);
else if (unnamedAny == null)
unnamedAny = element;
}
else if (choice != null)
{
string fullTypeName = element.Mapping!.TypeDesc!.CSharpName;
object? enumValue;
string enumFullName = $"{enumTypeName}.@{FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue)}";
if (wroteFirstIf) ilg.InitElseIf();
else { wroteFirstIf = true; ilg.InitIf(); }
ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type);
ilg.Load(enumValue);
ilg.Ceq();
if (isNullable && !element.IsNullable)
{
Label labelFalse = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
ilg.Brfalse(labelFalse);
source.Load(typeof(object));
ilg.Load(null);
ilg.Cne();
ilg.Br_S(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
}
ilg.AndIf();
WriteChoiceTypeCheck(source, fullTypeName, choice!, enumFullName, element.Mapping.TypeDesc);
SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc);
WriteElement(element.Any ? source : castedSource, element, arrayName, writeAccessors);
}
else
{
TypeDesc td = element.IsUnbounded ? element.Mapping!.TypeDesc!.CreateArrayTypeDesc() : element.Mapping!.TypeDesc!;
if (wroteFirstIf) ilg.InitElseIf();
else { wroteFirstIf = true; ilg.InitIf(); }
WriteInstanceOf(source, td.Type!);
// WriteInstanceOf leave bool on the stack
ilg.AndIf();
SourceInfo castedSource = source.CastTo(td);
WriteElement(element.Any ? source : castedSource, element, arrayName, writeAccessors);
}
}
if (wroteFirstIf)
{
if (anyCount > 0)
{
// See "else " below
if (elements.Length - anyCount > 0)
{ // NOOP
}
else ilg.EndIf();
}
}
if (anyCount > 0)
{
if (elements.Length - anyCount > 0) ilg.InitElseIf();
else ilg.InitIf();
source.Load(typeof(object));
ilg.IsInst(typeof(XmlElement));
ilg.Load(null);
ilg.Cne();
ilg.AndIf();
LocalBuilder elemLoc = ilg.DeclareLocal(typeof(XmlElement), "elem");
source.Load(typeof(XmlElement));
ilg.Stloc(elemLoc);
int c = 0;
foreach (ElementAccessor element in namedAnys)
{
if (c++ > 0) ilg.InitElseIf();
else ilg.InitIf();
string? enumFullName = null;
Label labelEnd, labelFalse;
if (choice != null)
{
object? enumValue;
enumFullName = $"{enumTypeName}.@{FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue)}";
labelFalse = ilg.DefineLabel();
labelEnd = ilg.DefineLabel();
ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type);
ilg.Load(enumValue);
ilg.Bne(labelFalse);
if (isNullable && !element.IsNullable)
{
source.Load(typeof(object));
ilg.Load(null);
ilg.Cne();
}
else
{
ilg.Ldc(true);
}
ilg.Br(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
ilg.AndIf();
}
labelFalse = ilg.DefineLabel();
labelEnd = ilg.DefineLabel();
MethodInfo XmlNode_get_Name = typeof(XmlNode).GetMethod(
"get_Name",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod(
"get_NamespaceURI",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_Name);
ilg.Ldstr(GetCSharpString(element.Name));
MethodInfo String_op_Equality = typeof(string).GetMethod(
"op_Equality",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Call(String_op_Equality);
ilg.Brfalse(labelFalse);
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_NamespaceURI);
ilg.Ldstr(GetCSharpString(element.Namespace));
ilg.Call(String_op_Equality);
ilg.Br(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
if (choice != null) ilg.If();
else ilg.AndIf();
WriteElement(new SourceInfo("elem", null, null, elemLoc.LocalType, ilg), element, arrayName, writeAccessors);
if (choice != null)
{
ilg.Else();
MethodInfo XmlSerializationWriter_CreateChoiceIdentifierValueException = typeof(XmlSerializationWriter).GetMethod(
"CreateChoiceIdentifierValueException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(enumFullName));
ilg.Ldstr(GetCSharpString(choice.MemberName));
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_Name);
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_NamespaceURI);
ilg.Call(XmlSerializationWriter_CreateChoiceIdentifierValueException);
ilg.Throw();
ilg.EndIf();
}
}
if (c > 0)
{
ilg.Else();
}
if (unnamedAny != null)
{
WriteElement(new SourceInfo("elem", null, null, elemLoc.LocalType, ilg), unnamedAny, arrayName, writeAccessors);
}
else
{
MethodInfo XmlSerializationWriter_CreateUnknownAnyElementException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownAnyElementException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldloc(elemLoc);
MethodInfo XmlNode_get_Name = typeof(XmlNode).GetMethod(
"get_Name",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod(
"get_NamespaceURI",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
ilg.Call(XmlNode_get_Name);
ilg.Ldloc(elemLoc);
ilg.Call(XmlNode_get_NamespaceURI);
ilg.Call(XmlSerializationWriter_CreateUnknownAnyElementException);
ilg.Throw();
}
if (c > 0)
{
ilg.EndIf();
}
}
if (text != null)
{
if (elements.Length > 0)
{
ilg.InitElseIf();
WriteInstanceOf(source, text.Mapping!.TypeDesc!.Type!);
ilg.AndIf();
SourceInfo castedSource = source.CastTo(text.Mapping.TypeDesc);
WriteText(castedSource, text);
}
else
{
SourceInfo castedSource = source.CastTo(text.Mapping!.TypeDesc!);
WriteText(castedSource, text);
}
}
if (elements.Length > 0)
{
if (isNullable)
{
ilg.InitElseIf();
source.Load(null);
ilg.Load(null);
ilg.AndIf(Cmp.NotEqualTo);
}
else
{
ilg.Else();
}
MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateUnknownTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) })!;
ilg.Ldarg(0);
source.Load(typeof(object));
ilg.Call(XmlSerializationWriter_CreateUnknownTypeException);
ilg.Throw();
ilg.EndIf();
}
// See ilg.If() cond above
if (doEndIf) // if (isNullable && choice == null)
ilg.EndIf();
}
}
[RequiresUnreferencedCode("calls Load")]
private void WriteText(SourceInfo source, TextAccessor text)
{
if (text.Mapping is PrimitiveMapping)
{
PrimitiveMapping mapping = (PrimitiveMapping)text.Mapping;
Type argType;
ilg.Ldarg(0);
if (text.Mapping is EnumMapping)
{
WriteEnumValue((EnumMapping)text.Mapping, source, out argType);
}
else
{
WritePrimitiveValue(mapping.TypeDesc!, source, out argType);
}
MethodInfo XmlSerializationWriter_WriteValue = typeof(XmlSerializationWriter).GetMethod(
"WriteValue",
CodeGenerator.InstanceBindingFlags,
new Type[] { argType }
)!;
ilg.Call(XmlSerializationWriter_WriteValue);
}
else if (text.Mapping is SpecialMapping)
{
SpecialMapping mapping = (SpecialMapping)text.Mapping;
switch (mapping.TypeDesc!.Kind)
{
case TypeKind.Node:
MethodInfo WriteTo = source.Type!.GetMethod(
"WriteTo",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(XmlWriter) }
)!;
MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod(
"get_Writer",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
source.Load(source.Type);
ilg.Ldarg(0);
ilg.Call(XmlSerializationWriter_get_Writer);
ilg.Call(WriteTo);
break;
default:
throw new InvalidOperationException(SR.XmlInternalError);
}
}
}
[RequiresUnreferencedCode("Calls WriteCheckDefault")]
private void WriteElement(SourceInfo source, ElementAccessor element, string arrayName, bool writeAccessor)
{
string name = writeAccessor ? element.Name : element.Mapping!.TypeName!;
string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : "");
if (element.Mapping is NullableMapping)
{
if (source.Type == element.Mapping.TypeDesc!.Type)
{
MethodInfo Nullable_get_HasValue = element.Mapping.TypeDesc.Type!.GetMethod(
"get_HasValue",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
source.LoadAddress(element.Mapping.TypeDesc.Type);
ilg.Call(Nullable_get_HasValue);
}
else
{
source.Load(null);
ilg.Load(null);
ilg.Cne();
}
ilg.If();
SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc.BaseTypeDesc!);
ElementAccessor e = element.Clone();
e.Mapping = ((NullableMapping)element.Mapping).BaseMapping;
WriteElement(e.Any ? source : castedSource, e, arrayName, writeAccessor);
if (element.IsNullable)
{
ilg.Else();
WriteLiteralNullTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : "");
}
ilg.EndIf();
}
else if (element.Mapping is ArrayMapping)
{
ArrayMapping mapping = (ArrayMapping)element.Mapping;
if (element.IsUnbounded)
{
throw Globals.NotSupported("Unreachable: IsUnbounded is never set true!");
}
else
{
ilg.EnterScope();
string fullTypeName = mapping.TypeDesc!.CSharpName;
WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc);
if (element.IsNullable)
{
WriteNullCheckBegin(arrayName, element);
}
else
{
if (mapping.TypeDesc.IsNullable)
{
ilg.Ldloc(ilg.GetLocal(arrayName));
ilg.Load(null);
ilg.If(Cmp.NotEqualTo);
}
}
WriteStartElement(name, ns, false);
WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null);
WriteEndElement();
if (element.IsNullable)
{
ilg.EndIf();
}
else
{
if (mapping.TypeDesc.IsNullable)
{
ilg.EndIf();
}
}
ilg.ExitScope();
}
}
else if (element.Mapping is EnumMapping)
{
WritePrimitive("WriteElementString", name, ns, element.Default, source, element.Mapping, false, true, element.IsNullable);
}
else if (element.Mapping is PrimitiveMapping)
{
PrimitiveMapping mapping = (PrimitiveMapping)element.Mapping;
if (mapping.TypeDesc == QnameTypeDesc)
WriteQualifiedNameElement(name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, element.IsNullable, mapping);
else
{
string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : "";
WritePrimitive(element.IsNullable ? ("WriteNullableStringLiteral" + suffixRaw) : ("WriteElementString" + suffixRaw),
name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, mapping, false, true, element.IsNullable);
}
}
else if (element.Mapping is StructMapping)
{
StructMapping mapping = (StructMapping)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
List<Type> argTypes = new List<Type>();
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(name));
argTypes.Add(typeof(string));
ilg.Ldstr(GetCSharpString(ns));
argTypes.Add(typeof(string));
source.Load(mapping.TypeDesc!.Type);
argTypes.Add(mapping.TypeDesc.Type!);
if (mapping.TypeDesc.IsNullable)
{
ilg.Ldc(element.IsNullable);
argTypes.Add(typeof(bool));
}
ilg.Ldc(false);
argTypes.Add(typeof(bool));
MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder,
methodName!,
CodeGenerator.PrivateMethodAttributes,
typeof(void),
argTypes.ToArray());
ilg.Call(methodBuilder);
}
else if (element.Mapping is SpecialMapping)
{
if (element.Mapping is SerializableMapping)
{
WriteElementCall("WriteSerializable", typeof(IXmlSerializable), source, name, ns, element.IsNullable, !element.Any);
}
else
{
// XmlNode, XmlElement
Label ifLabel1 = ilg.DefineLabel();
Label ifLabel2 = ilg.DefineLabel();
source.Load(null);
ilg.IsInst(typeof(XmlNode));
ilg.Brtrue(ifLabel1);
source.Load(null);
ilg.Load(null);
ilg.Ceq();
ilg.Br(ifLabel2);
ilg.MarkLabel(ifLabel1);
ilg.Ldc(true);
ilg.MarkLabel(ifLabel2);
ilg.If();
WriteElementCall("WriteElementLiteral", typeof(XmlNode), source, name, ns, element.IsNullable, element.Any);
ilg.Else();
MethodInfo XmlSerializationWriter_CreateInvalidAnyTypeException = typeof(XmlSerializationWriter).GetMethod(
"CreateInvalidAnyTypeException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(object) }
)!;
ilg.Ldarg(0);
source.Load(null);
ilg.Call(XmlSerializationWriter_CreateInvalidAnyTypeException);
ilg.Throw();
ilg.EndIf();
}
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
[RequiresUnreferencedCode("XmlSerializationWriter methods have RequiresUnreferencedCode")]
private void WriteElementCall(string func, Type cast, SourceInfo source, string? name, string? ns, bool isNullable, bool isAny)
{
MethodInfo XmlSerializationWriter_func = typeof(XmlSerializationWriter).GetMethod(
func,
CodeGenerator.InstanceBindingFlags,
new Type[] { cast, typeof(string), typeof(string), typeof(bool), typeof(bool) }
)!;
ilg.Ldarg(0);
source.Load(cast);
ilg.Ldstr(GetCSharpString(name));
ilg.Ldstr(GetCSharpString(ns));
ilg.Ldc(isNullable);
ilg.Ldc(isAny);
ilg.Call(XmlSerializationWriter_func);
}
[RequiresUnreferencedCode("Dynamically looks for '!=' operator on 'value' parameter")]
private void WriteCheckDefault(SourceInfo source, object value, bool isNullable)
{
if (value is string && ((string)value).Length == 0)
{
// special case for string compare
Label labelEnd = ilg.DefineLabel();
Label labelFalse = ilg.DefineLabel();
Label labelTrue = ilg.DefineLabel();
source.Load(typeof(string));
if (isNullable)
// check == null with false
ilg.Brfalse(labelTrue);
else
//check != null with false
ilg.Brfalse(labelFalse);
MethodInfo String_get_Length = typeof(string).GetMethod(
"get_Length",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
source.Load(typeof(string));
ilg.Call(String_get_Length);
ilg.Ldc(0);
ilg.Cne();
ilg.Br(labelEnd);
if (isNullable)
{
ilg.MarkLabel(labelTrue);
ilg.Ldc(true);
}
else
{
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
}
ilg.MarkLabel(labelEnd);
ilg.If();
}
else
{
if (value == null)
{
source.Load(typeof(object));
ilg.Load(null);
ilg.Cne();
}
else if (value.GetType().IsPrimitive)
{
source.Load(null);
ilg.Ldc(Convert.ChangeType(value, source.Type!, CultureInfo.InvariantCulture));
ilg.Cne();
}
else
{
Type valueType = value.GetType();
source.Load(valueType);
ilg.Ldc(value is string ? GetCSharpString((string)value) : value);
MethodInfo op_Inequality = valueType.GetMethod(
"op_Inequality",
CodeGenerator.StaticBindingFlags,
new Type[] { valueType, valueType }
)!;
if (op_Inequality != null)
ilg.Call(op_Inequality);
else
ilg.Cne();
}
ilg.If();
}
}
[RequiresUnreferencedCode("calls Load")]
private void WriteChoiceTypeCheck(SourceInfo source, string fullTypeName, ChoiceIdentifierAccessor choice, string enumName, TypeDesc typeDesc)
{
Label labelFalse = ilg.DefineLabel();
Label labelEnd = ilg.DefineLabel();
source.Load(typeof(object));
ilg.Load(null);
ilg.Beq(labelFalse);
WriteInstanceOf(source, typeDesc.Type!);
// Negative
ilg.Ldc(false);
ilg.Ceq();
ilg.Br(labelEnd);
ilg.MarkLabel(labelFalse);
ilg.Ldc(false);
ilg.MarkLabel(labelEnd);
ilg.If();
MethodInfo XmlSerializationWriter_CreateMismatchChoiceException = typeof(XmlSerializationWriter).GetMethod(
"CreateMismatchChoiceException",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(string), typeof(string), typeof(string) }
)!;
ilg.Ldarg(0);
ilg.Ldstr(GetCSharpString(typeDesc.FullName));
ilg.Ldstr(GetCSharpString(choice.MemberName));
ilg.Ldstr(GetCSharpString(enumName));
ilg.Call(XmlSerializationWriter_CreateMismatchChoiceException);
ilg.Throw();
ilg.EndIf();
}
[RequiresUnreferencedCode("calls WriteLiteralNullTag")]
private void WriteNullCheckBegin(string source, ElementAccessor element)
{
LocalBuilder local = ilg.GetLocal(source);
Debug.Assert(!local.LocalType.IsValueType);
ilg.Load(local);
ilg.Load(null);
ilg.If(Cmp.EqualTo);
WriteLiteralNullTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : "");
ilg.Else();
}
[RequiresUnreferencedCode("calls ILGenLoad")]
private void WriteNamespaces(string source)
{
MethodInfo XmlSerializationWriter_WriteNamespaceDeclarations = typeof(XmlSerializationWriter).GetMethod(
"WriteNamespaceDeclarations",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(XmlSerializerNamespaces) }
)!;
ilg.Ldarg(0);
ILGenLoad(source, typeof(XmlSerializerNamespaces));
ilg.Call(XmlSerializationWriter_WriteNamespaceDeclarations);
}
private int FindXmlnsIndex(MemberMapping[] members)
{
for (int i = 0; i < members.Length; i++)
{
if (members[i].Xmlns == null)
continue;
return i;
}
return -1;
}
[RequiresUnreferencedCode("calls WriteLocalDecl")]
private void WriteLocalDecl(string variableName, string initValue, Type type)
{
RaCodeGen.WriteLocalDecl(variableName, new SourceInfo(initValue, initValue, null, type, ilg));
}
[RequiresUnreferencedCode("calls WriteArrayLocalDecl")]
private void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc)
{
RaCodeGen.WriteArrayLocalDecl(typeName, variableName, initValue, arrayTypeDesc);
}
private void WriteTypeCompare(string variable, Type type)
{
RaCodeGen.WriteTypeCompare(variable, type, ilg);
}
[RequiresUnreferencedCode("calls WriteInstanceOf")]
private void WriteInstanceOf(SourceInfo source, Type type)
{
RaCodeGen.WriteInstanceOf(source, type, ilg);
}
private void WriteArrayTypeCompare(string variable, Type arrayType)
{
RaCodeGen.WriteArrayTypeCompare(variable, arrayType, ilg);
}
private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object? eValue)
{
string? enumValue = null;
eValue = null;
for (int i = 0; i < choiceMapping.Constants!.Length; i++)
{
string xmlName = choiceMapping.Constants[i].XmlName;
if (element.Any && element.Name.Length == 0)
{
if (xmlName == "##any:")
{
enumValue = choiceMapping.Constants[i].Name;
eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value);
break;
}
continue;
}
int colon = xmlName.LastIndexOf(':');
string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon);
string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1);
if (element.Name == choiceName)
{
if ((element.Form == XmlSchemaForm.Unqualified && string.IsNullOrEmpty(choiceNs)) || element.Namespace == choiceNs)
{
enumValue = choiceMapping.Constants[i].Name;
eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value);
break;
}
}
}
if (enumValue == null || enumValue.Length == 0)
{
if (element.Any && element.Name.Length == 0)
{
// Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute.
throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc!.FullName));
}
// Type {0} is missing value for '{1}'.
throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc!.FullName, $"{element.Namespace}:{element.Name}", element.Name, element.Namespace));
}
CodeIdentifier.CheckValidIdentifier(enumValue);
return enumValue;
}
}
internal sealed class ReflectionAwareILGen
{
// reflectionVariables holds mapping between a reflection entity
// referenced in the generated code (such as TypeInfo,
// FieldInfo) and the variable which represent the entity (and
// initialized before).
// The types of reflection entity and corresponding key is
// given below.
// ----------------------------------------------------------------------------------
// Entity Key
// ----------------------------------------------------------------------------------
// Assembly assembly.FullName
// Type CodeIdentifier.EscapedKeywords(type.FullName)
// Field fieldName+":"+CodeIdentifier.EscapedKeywords(containingType.FullName>)
// Property propertyName+":"+CodeIdentifier.EscapedKeywords(containingType.FullName)
// ArrayAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(Array).FullName)
// MyCollectionAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(MyCollection).FullName)
// ----------------------------------------------------------------------------------
internal ReflectionAwareILGen() { }
[RequiresUnreferencedCode("calls GetTypeDesc")]
internal void WriteReflectionInit(TypeScope scope)
{
foreach (Type type in scope.Types)
{
scope.GetTypeDesc(type);
}
}
internal void ILGenForEnumLongValue(CodeGenerator ilg, string variable)
{
ArgBuilder argV = ilg.GetArg(variable);
ilg.Ldarg(argV);
ilg.ConvertValue(argV.ArgType, typeof(long));
}
internal string GetStringForTypeof(string typeFullName)
{
{
return $"typeof({typeFullName})";
}
}
internal string GetStringForMember(string obj, string memberName, TypeDesc typeDesc)
{
return $"{obj}.@{memberName}";
}
internal SourceInfo GetSourceForMember(string obj, MemberMapping member, TypeDesc typeDesc, CodeGenerator ilg)
{
return GetSourceForMember(obj, member, member.MemberInfo, typeDesc, ilg);
}
internal SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, TypeDesc typeDesc, CodeGenerator ilg)
{
return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc!.Type, ilg);
}
internal void ILGenForEnumMember(CodeGenerator ilg, Type type, string memberName)
{
ilg.Ldc(Enum.Parse(type, memberName, false));
}
internal string GetStringForArrayMember(string? arrayName, string subscript, TypeDesc arrayTypeDesc)
{
{
return $"{arrayName}[{subscript}]";
}
}
internal string GetStringForMethod(string obj, string typeFullName, string memberName)
{
return $"{obj}.{memberName}(";
}
[RequiresUnreferencedCode("calls ILGenForCreateInstance")]
internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInaccessible, bool cast)
{
if (!ctorInaccessible)
{
ConstructorInfo ctor = type.GetConstructor(
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes
)!;
if (ctor != null)
ilg.New(ctor);
else
{
Debug.Assert(type.IsValueType);
LocalBuilder tmpLoc = ilg.GetTempLocal(type);
ilg.Ldloca(tmpLoc);
ilg.InitObj(type);
ilg.Ldloc(tmpLoc);
}
return;
}
ILGenForCreateInstance(ilg, type, cast ? type : null, ctorInaccessible);
}
[RequiresUnreferencedCode("calls GetType")]
internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, bool nonPublic)
{
// Special case DBNull
if (type == typeof(DBNull))
{
FieldInfo DBNull_Value = type.GetField("Value", CodeGenerator.StaticBindingFlags)!;
ilg.LoadMember(DBNull_Value);
return;
}
// Special case XElement
// codegen the same as 'internal XElement : this("default") { }'
if (type.FullName == "System.Xml.Linq.XElement")
{
Type? xName = type.Assembly.GetType("System.Xml.Linq.XName");
if (xName != null)
{
MethodInfo XName_op_Implicit = xName.GetMethod(
"op_Implicit",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(string) }
)!;
ConstructorInfo XElement_ctor = type.GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { xName }
)!;
if (XName_op_Implicit != null && XElement_ctor != null)
{
ilg.Ldstr("default");
ilg.Call(XName_op_Implicit);
ilg.New(XElement_ctor);
return;
}
}
}
Label labelReturn = ilg.DefineLabel();
Label labelEndIf = ilg.DefineLabel();
// TypeInfo typeInfo = type.GetTypeInfo();
// typeInfo not declared explicitly
ilg.Ldc(type);
MethodInfo getTypeInfoMehod = typeof(IntrospectionExtensions).GetMethod(
"GetTypeInfo",
CodeGenerator.StaticBindingFlags,
new[] { typeof(Type) }
)!;
ilg.Call(getTypeInfoMehod);
// IEnumerator<ConstructorInfo> e = typeInfo.DeclaredConstructors.GetEnumerator();
LocalBuilder enumerator = ilg.DeclareLocal(typeof(IEnumerator<>).MakeGenericType(typeof(ConstructorInfo)), "e");
MethodInfo getDeclaredConstructors = typeof(TypeInfo).GetMethod("get_DeclaredConstructors")!;
MethodInfo getEnumerator = typeof(IEnumerable<>).MakeGenericType(typeof(ConstructorInfo)).GetMethod("GetEnumerator")!;
ilg.Call(getDeclaredConstructors);
ilg.Call(getEnumerator);
ilg.Stloc(enumerator);
ilg.WhileBegin();
// ConstructorInfo constructorInfo = e.Current();
MethodInfo enumeratorCurrent = typeof(IEnumerator).GetMethod("get_Current")!;
ilg.Ldloc(enumerator);
ilg.Call(enumeratorCurrent);
LocalBuilder constructorInfo = ilg.DeclareLocal(typeof(ConstructorInfo), "constructorInfo");
ilg.Stloc(constructorInfo);
// if (!constructorInfo.IsStatic && constructorInfo.GetParameters.Length() == 0)
ilg.Ldloc(constructorInfo);
MethodInfo constructorIsStatic = typeof(ConstructorInfo).GetMethod("get_IsStatic")!;
ilg.Call(constructorIsStatic);
ilg.Brtrue(labelEndIf);
ilg.Ldloc(constructorInfo);
MethodInfo constructorGetParameters = typeof(ConstructorInfo).GetMethod("GetParameters")!;
ilg.Call(constructorGetParameters);
ilg.Ldlen();
ilg.Ldc(0);
ilg.Cne();
ilg.Brtrue(labelEndIf);
// constructorInfo.Invoke(null);
MethodInfo constructorInvoke = typeof(ConstructorInfo).GetMethod("Invoke", new Type[] { typeof(object[]) })!;
ilg.Ldloc(constructorInfo);
ilg.Load(null);
ilg.Call(constructorInvoke);
ilg.Br(labelReturn);
ilg.MarkLabel(labelEndIf);
ilg.WhileBeginCondition(); // while (e.MoveNext())
MethodInfo IEnumeratorMoveNext = typeof(IEnumerator).GetMethod(
"MoveNext",
CodeGenerator.InstanceBindingFlags,
Type.EmptyTypes)!;
ilg.Ldloc(enumerator);
ilg.Call(IEnumeratorMoveNext);
ilg.WhileEndCondition();
ilg.WhileEnd();
MethodInfo Activator_CreateInstance = typeof(Activator).GetMethod(
"CreateInstance",
CodeGenerator.StaticBindingFlags,
new Type[] { typeof(Type) }
)!;
ilg.Ldc(type);
ilg.Call(Activator_CreateInstance);
ilg.MarkLabel(labelReturn);
if (cast != null)
ilg.ConvertValue(Activator_CreateInstance.ReturnType, cast);
}
[RequiresUnreferencedCode("calls LoadMember")]
internal void WriteLocalDecl(string variableName, SourceInfo initValue)
{
Type localType = initValue.Type!;
LocalBuilder localA = initValue.ILG.DeclareOrGetLocal(localType, variableName);
if (initValue.Source != null)
{
if (initValue == "null")
{
initValue.ILG.Load(null);
}
else
{
if (initValue.Arg.StartsWith("o.@", StringComparison.Ordinal))
{
Debug.Assert(initValue.MemberInfo != null);
Debug.Assert(initValue.MemberInfo.Name == initValue.Arg.Substring(3));
initValue.ILG.LoadMember(initValue.ILG.GetLocal("o"), initValue.MemberInfo);
}
else if (initValue.Source.EndsWith(']'))
{
initValue.Load(initValue.Type);
}
else if (initValue.Source == "fixup.Source" || initValue.Source == "e.Current")
{
string[] vars = initValue.Source.Split('.');
object fixup = initValue.ILG.GetVariable(vars[0]);
PropertyInfo propInfo = initValue.ILG.GetVariableType(fixup).GetProperty(vars[1])!;
initValue.ILG.LoadMember(fixup, propInfo);
initValue.ILG.ConvertValue(propInfo.PropertyType, localA.LocalType);
}
else
{
object sVar = initValue.ILG.GetVariable(initValue.Arg);
initValue.ILG.Load(sVar);
initValue.ILG.ConvertValue(initValue.ILG.GetVariableType(sVar), localA.LocalType);
}
}
initValue.ILG.Stloc(localA);
}
}
[RequiresUnreferencedCode("calls ILGenForCreateInstance")]
internal void WriteCreateInstance(string source, bool ctorInaccessible, Type type, CodeGenerator ilg)
{
LocalBuilder sLoc = ilg.DeclareOrGetLocal(type, source);
ILGenForCreateInstance(ilg, type, ctorInaccessible, ctorInaccessible);
ilg.Stloc(sLoc);
}
[RequiresUnreferencedCode("calls Load")]
internal void WriteInstanceOf(SourceInfo source, Type type, CodeGenerator ilg)
{
{
source.Load(typeof(object));
ilg.IsInst(type);
ilg.Load(null);
ilg.Cne();
return;
}
}
[RequiresUnreferencedCode("calls Load")]
internal void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc)
{
Debug.Assert(typeName == arrayTypeDesc.CSharpName || typeName == $"{arrayTypeDesc.CSharpName}[]");
Type localType = (typeName == arrayTypeDesc.CSharpName) ? arrayTypeDesc.Type! : arrayTypeDesc.Type!.MakeArrayType();
// This may need reused variable to get code compat?
LocalBuilder local = initValue.ILG.DeclareOrGetLocal(localType, variableName);
if (initValue != null)
{
initValue.Load(local.LocalType);
initValue.ILG.Stloc(local);
}
}
internal void WriteTypeCompare(string variable, Type type, CodeGenerator ilg)
{
Debug.Assert(type != null);
Debug.Assert(ilg != null);
ilg.Ldloc(typeof(Type), variable);
ilg.Ldc(type);
ilg.Ceq();
}
internal void WriteArrayTypeCompare(string variable, Type arrayType, CodeGenerator ilg)
{
{
Debug.Assert(arrayType != null);
Debug.Assert(ilg != null);
ilg.Ldloc(typeof(Type), variable);
ilg.Ldc(arrayType);
ilg.Ceq();
return;
}
}
[return: NotNullIfNotNull("value")]
internal static string? GetQuotedCSharpString(string? value)
{
if (value == null)
{
return null;
}
StringBuilder writer = new StringBuilder();
writer.Append("@\"");
writer.Append(GetCSharpString(value));
writer.Append('"');
return writer.ToString();
}
[return: NotNullIfNotNull("value")]
internal static string? GetCSharpString(string? value)
{
if (value == null)
{
return null;
}
StringBuilder writer = new StringBuilder();
foreach (char ch in value)
{
if (ch < 32)
{
if (ch == '\r')
writer.Append("\\r");
else if (ch == '\n')
writer.Append("\\n");
else if (ch == '\t')
writer.Append("\\t");
else
{
byte b = (byte)ch;
writer.Append("\\x");
writer.Append(HexConverter.ToCharUpper(b >> 4));
writer.Append(HexConverter.ToCharUpper(b));
}
}
else if (ch == '\"')
{
writer.Append("\"\"");
}
else
{
writer.Append(ch);
}
}
return writer.ToString();
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Data.Common/src/System/Data/Constraint.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.Data
{
/// <summary>
/// Represents a constraint that can be enforced on one or more <see cref='System.Data.DataColumn'/> objects.
/// </summary>
[DefaultProperty(nameof(ConstraintName))]
[TypeConverter(typeof(ConstraintConverter))]
public abstract class Constraint
{
private string _schemaName = string.Empty;
private bool _inCollection;
private DataSet? _dataSet;
internal string _name = string.Empty;
internal PropertyCollection? _extendedProperties;
internal Constraint() { }
/// <summary>
/// The name of this constraint within the <see cref='System.Data.ConstraintCollection'/>.
/// </summary>
[DefaultValue("")]
[AllowNull]
public virtual string ConstraintName
{
get { return _name; }
set
{
if (value == null)
{
value = string.Empty;
}
if (string.IsNullOrEmpty(value) && (Table != null) && InCollection)
{
throw ExceptionBuilder.NoConstraintName();
}
CultureInfo locale = (Table != null ? Table.Locale : CultureInfo.CurrentCulture);
if (string.Compare(_name, value, true, locale) != 0)
{
if ((Table != null) && InCollection)
{
Table.Constraints.RegisterName(value);
if (_name.Length != 0)
Table.Constraints.UnregisterName(_name);
}
_name = value;
}
else if (string.Compare(_name, value, false, locale) != 0)
{
_name = value;
}
}
}
internal string SchemaName
{
get { return string.IsNullOrEmpty(_schemaName) ? ConstraintName : _schemaName; }
set
{
if (!string.IsNullOrEmpty(value))
{
_schemaName = value;
}
}
}
internal virtual bool InCollection
{
get { return _inCollection; }
set
{
_inCollection = value;
_dataSet = value ? Table!.DataSet : null;
}
}
/// <summary>
/// Gets the <see cref='System.Data.DataTable'/> to which the constraint applies.
/// </summary>
public abstract DataTable? Table { get; }
/// <summary>
/// Gets the collection of customized user information.
/// </summary>
[Browsable(false)]
public PropertyCollection ExtendedProperties => _extendedProperties ?? (_extendedProperties = new PropertyCollection());
internal abstract bool ContainsColumn(DataColumn column);
internal abstract bool CanEnableConstraint();
internal abstract Constraint? Clone(DataSet destination);
internal abstract Constraint? Clone(DataSet destination, bool ignoreNSforTableLookup);
internal void CheckConstraint()
{
if (!CanEnableConstraint())
{
throw ExceptionBuilder.ConstraintViolation(ConstraintName);
}
}
internal abstract void CheckCanAddToCollection(ConstraintCollection constraint);
internal abstract bool CanBeRemovedFromCollection(ConstraintCollection constraint, bool fThrowException);
internal abstract void CheckConstraint(DataRow row, DataRowAction action);
internal abstract void CheckState();
protected void CheckStateForProperty()
{
try
{
CheckState();
}
catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e))
{
throw ExceptionBuilder.BadObjectPropertyAccess(e.Message);
}
}
/// <summary>
/// Gets the <see cref='System.Data.DataSet'/> to which this constraint belongs.
/// </summary>
[CLSCompliant(false)]
protected virtual DataSet? _DataSet => _dataSet;
/// <summary>
/// Sets the constraint's <see cref='System.Data.DataSet'/>.
/// </summary>
protected internal void SetDataSet(DataSet dataSet) => _dataSet = dataSet;
internal abstract bool IsConstraintViolated();
public override string ToString() => ConstraintName;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.Data
{
/// <summary>
/// Represents a constraint that can be enforced on one or more <see cref='System.Data.DataColumn'/> objects.
/// </summary>
[DefaultProperty(nameof(ConstraintName))]
[TypeConverter(typeof(ConstraintConverter))]
public abstract class Constraint
{
private string _schemaName = string.Empty;
private bool _inCollection;
private DataSet? _dataSet;
internal string _name = string.Empty;
internal PropertyCollection? _extendedProperties;
internal Constraint() { }
/// <summary>
/// The name of this constraint within the <see cref='System.Data.ConstraintCollection'/>.
/// </summary>
[DefaultValue("")]
[AllowNull]
public virtual string ConstraintName
{
get { return _name; }
set
{
if (value == null)
{
value = string.Empty;
}
if (string.IsNullOrEmpty(value) && (Table != null) && InCollection)
{
throw ExceptionBuilder.NoConstraintName();
}
CultureInfo locale = (Table != null ? Table.Locale : CultureInfo.CurrentCulture);
if (string.Compare(_name, value, true, locale) != 0)
{
if ((Table != null) && InCollection)
{
Table.Constraints.RegisterName(value);
if (_name.Length != 0)
Table.Constraints.UnregisterName(_name);
}
_name = value;
}
else if (string.Compare(_name, value, false, locale) != 0)
{
_name = value;
}
}
}
internal string SchemaName
{
get { return string.IsNullOrEmpty(_schemaName) ? ConstraintName : _schemaName; }
set
{
if (!string.IsNullOrEmpty(value))
{
_schemaName = value;
}
}
}
internal virtual bool InCollection
{
get { return _inCollection; }
set
{
_inCollection = value;
_dataSet = value ? Table!.DataSet : null;
}
}
/// <summary>
/// Gets the <see cref='System.Data.DataTable'/> to which the constraint applies.
/// </summary>
public abstract DataTable? Table { get; }
/// <summary>
/// Gets the collection of customized user information.
/// </summary>
[Browsable(false)]
public PropertyCollection ExtendedProperties => _extendedProperties ?? (_extendedProperties = new PropertyCollection());
internal abstract bool ContainsColumn(DataColumn column);
internal abstract bool CanEnableConstraint();
internal abstract Constraint? Clone(DataSet destination);
internal abstract Constraint? Clone(DataSet destination, bool ignoreNSforTableLookup);
internal void CheckConstraint()
{
if (!CanEnableConstraint())
{
throw ExceptionBuilder.ConstraintViolation(ConstraintName);
}
}
internal abstract void CheckCanAddToCollection(ConstraintCollection constraint);
internal abstract bool CanBeRemovedFromCollection(ConstraintCollection constraint, bool fThrowException);
internal abstract void CheckConstraint(DataRow row, DataRowAction action);
internal abstract void CheckState();
protected void CheckStateForProperty()
{
try
{
CheckState();
}
catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e))
{
throw ExceptionBuilder.BadObjectPropertyAccess(e.Message);
}
}
/// <summary>
/// Gets the <see cref='System.Data.DataSet'/> to which this constraint belongs.
/// </summary>
[CLSCompliant(false)]
protected virtual DataSet? _DataSet => _dataSet;
/// <summary>
/// Sets the constraint's <see cref='System.Data.DataSet'/>.
/// </summary>
protected internal void SetDataSet(DataSet dataSet) => _dataSet = dataSet;
internal abstract bool IsConstraintViolated();
public override string ToString() => ConstraintName;
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CertUsageType.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.Security.Cryptography.Xml
{
internal enum CertUsageType
{
Verification = 0,
Decryption = 1
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Security.Cryptography.Xml
{
internal enum CertUsageType
{
Verification = 0,
Decryption = 1
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/EncryptDecrypt.netcoreapp.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using Xunit;
namespace System.Security.Cryptography.Rsa.Tests
{
[SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")]
public sealed class EncryptDecrypt_Span : EncryptDecrypt
{
protected override byte[] Encrypt(RSA rsa, byte[] data, RSAEncryptionPadding padding) =>
TryWithOutputArray(dest => rsa.TryEncrypt(data, dest, padding, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
protected override byte[] Decrypt(RSA rsa, byte[] data, RSAEncryptionPadding padding) =>
TryWithOutputArray(dest => rsa.TryDecrypt(data, dest, padding, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
private static byte[] TryWithOutputArray(Func<byte[], (bool, int)> func)
{
for (int length = 1; ; length = checked(length * 2))
{
var result = new byte[length];
var (success, bytesWritten) = func(result);
if (success)
{
Array.Resize(ref result, bytesWritten);
return result;
}
}
}
[Fact]
public void Decrypt_VariousSizeSpans_Success()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
byte[] cipherBytes = Encrypt(rsa, TestData.HelloBytes, RSAEncryptionPadding.OaepSHA1);
byte[] actual;
int bytesWritten;
// Too small
actual = new byte[TestData.HelloBytes.Length - 1];
Assert.False(rsa.TryDecrypt(cipherBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(0, bytesWritten);
Assert.Equal<byte>(new byte[actual.Length], actual);
// Just right.
actual = new byte[TestData.HelloBytes.Length];
bool decrypted = rsa.TryDecrypt(cipherBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten);
Assert.True(decrypted);
Assert.Equal(TestData.HelloBytes.Length, bytesWritten);
Assert.Equal<byte>(TestData.HelloBytes, actual);
// Bigger than needed
actual = new byte[TestData.HelloBytes.Length + 1000];
Assert.True(rsa.TryDecrypt(cipherBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(TestData.HelloBytes.Length, bytesWritten);
Assert.Equal<byte>(TestData.HelloBytes, actual.AsSpan(0, TestData.HelloBytes.Length).ToArray());
}
}
[Fact]
public void Encrypt_VariousSizeSpans_Success()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
byte[] cipherBytes = Encrypt(rsa, TestData.HelloBytes, RSAEncryptionPadding.OaepSHA1);
byte[] actual;
int bytesWritten;
// Too small
actual = new byte[cipherBytes.Length - 1];
Assert.False(rsa.TryEncrypt(TestData.HelloBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(0, bytesWritten);
// Just right
actual = new byte[cipherBytes.Length];
Assert.True(rsa.TryEncrypt(TestData.HelloBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(cipherBytes.Length, bytesWritten);
// Bigger than needed
actual = new byte[cipherBytes.Length + 1];
Assert.True(rsa.TryEncrypt(TestData.HelloBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(cipherBytes.Length, bytesWritten);
}
}
[Fact]
public void Decrypt_WrongKey_Pkcs7()
{
Decrypt_WrongKey(RSAEncryptionPadding.Pkcs1);
}
[Fact]
public void Decrypt_WrongKey_OAEP_SHA1()
{
Decrypt_WrongKey(RSAEncryptionPadding.OaepSHA1);
}
[ConditionalFact(nameof(SupportsSha2Oaep))]
public void Decrypt_WrongKey_OAEP_SHA256()
{
Decrypt_WrongKey(RSAEncryptionPadding.OaepSHA256);
}
[Fact]
public static void EncryptDefaultSpan()
{
using (RSA rsa = RSAFactory.Create())
{
byte[] dest = new byte[rsa.KeySize / 8];
Assert.True(
rsa.TryEncrypt(ReadOnlySpan<byte>.Empty, dest, RSAEncryptionPadding.Pkcs1, out int written));
Assert.Equal(dest.Length, written);
Assert.True(
rsa.TryEncrypt(ReadOnlySpan<byte>.Empty, dest, RSAEncryptionPadding.OaepSHA1, out written));
Assert.Equal(dest.Length, written);
}
}
private static void Decrypt_WrongKey(RSAEncryptionPadding padding)
{
using (RSA rsa1 = RSAFactory.Create())
using (RSA rsa2 = RSAFactory.Create())
{
byte[] input = TestData.HelloBytes;
byte[] encrypted = rsa1.Encrypt(input, padding);
byte[] buf = new byte[encrypted.Length];
buf.AsSpan().Fill(0xCA);
int bytesWritten = 0;
// PKCS#1 padding allows for an incorrect response when the random key produces
// a start sequence of [ 00 02 !00 !00 !00 !00 !00 !00 !00 !00 ] with an eventual zero.
// 1/256 * 1/256 * (255/256)^8 is the start.
// 1 - (255/256)^(keySizeInBytes - 10) is the probability that there's an eventual zero.
// For RSA 2048, this works out to 9.142e-6, or 1 in 109385.
//
// OAEP is harder to reason about, it requires a bunch of data that hashes to a value
// that, XOR the remaining data, produces a value that is equivalent to a randomly
// generated number (which then runs through a formula and XORs back to "the input").
// The odds of that working are hard to say, but certainly much harder. Probably
// somewhere between 1 in 2^160 ("you made the right SHA-1 output") and 1 in 2^2048
// (you made the right private key). Since we already have the "if it succeeds, be wrong"
// code, just use it for OAEP, too.
try
{
// Because buf.Length >= ((rsa.KeySize / 8) - 11) (because it's rsa.KeySize / 8)
// false should never be returned.
//
// But if the padding doesn't work out (109384 out of 109385, see above) we'll throw.
bool decrypted = rsa2.TryDecrypt(encrypted, buf, padding, out bytesWritten);
Assert.True(decrypted, "Pkcs1 TryDecrypt succeeded with a large buffer");
// If bytesWritten != input.Length, we got back gibberish, which is good.
// If bytesWritten == input.Length then make sure at least one of the bytes is wrong.
// Probability time again.
// For RSA-2048, producing the input (ASCII("Hello")) requires a buffer of
// [ 00 02 248-nonzero-bytes 00 48 65 6C 6C 6F ]
// (1/256)^8 * (255/256)^248 = 3.2e-20, so this will fail 1 in 3.125e19 runs.
// One run a second => one failure every 990 billion years.
// (If our implementation is bad/weird, then all of these odds are meaningless, hence the test)
//
// For RSA-1024 (less freedom) it's 1 in 5.363e19, so like 1.6 trillion years.
if (rsa2.TryDecrypt(encrypted, buf, padding, out bytesWritten)
&& bytesWritten == input.Length)
{
// We'll get -here- 1 in 111014 runs (RSA-2048 Pkcs1).
Assert.NotEqual(input, buf.AsSpan(0, bytesWritten).ToArray());
}
}
catch (CryptographicException)
{
// 109384 out of 109385 times (RSA-2048 Pkcs1) we get here.
Assert.Equal(0, bytesWritten);
Assert.True(buf.All(b => b == 0xCA));
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using Xunit;
namespace System.Security.Cryptography.Rsa.Tests
{
[SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")]
public sealed class EncryptDecrypt_Span : EncryptDecrypt
{
protected override byte[] Encrypt(RSA rsa, byte[] data, RSAEncryptionPadding padding) =>
TryWithOutputArray(dest => rsa.TryEncrypt(data, dest, padding, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
protected override byte[] Decrypt(RSA rsa, byte[] data, RSAEncryptionPadding padding) =>
TryWithOutputArray(dest => rsa.TryDecrypt(data, dest, padding, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
private static byte[] TryWithOutputArray(Func<byte[], (bool, int)> func)
{
for (int length = 1; ; length = checked(length * 2))
{
var result = new byte[length];
var (success, bytesWritten) = func(result);
if (success)
{
Array.Resize(ref result, bytesWritten);
return result;
}
}
}
[Fact]
public void Decrypt_VariousSizeSpans_Success()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
byte[] cipherBytes = Encrypt(rsa, TestData.HelloBytes, RSAEncryptionPadding.OaepSHA1);
byte[] actual;
int bytesWritten;
// Too small
actual = new byte[TestData.HelloBytes.Length - 1];
Assert.False(rsa.TryDecrypt(cipherBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(0, bytesWritten);
Assert.Equal<byte>(new byte[actual.Length], actual);
// Just right.
actual = new byte[TestData.HelloBytes.Length];
bool decrypted = rsa.TryDecrypt(cipherBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten);
Assert.True(decrypted);
Assert.Equal(TestData.HelloBytes.Length, bytesWritten);
Assert.Equal<byte>(TestData.HelloBytes, actual);
// Bigger than needed
actual = new byte[TestData.HelloBytes.Length + 1000];
Assert.True(rsa.TryDecrypt(cipherBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(TestData.HelloBytes.Length, bytesWritten);
Assert.Equal<byte>(TestData.HelloBytes, actual.AsSpan(0, TestData.HelloBytes.Length).ToArray());
}
}
[Fact]
public void Encrypt_VariousSizeSpans_Success()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
byte[] cipherBytes = Encrypt(rsa, TestData.HelloBytes, RSAEncryptionPadding.OaepSHA1);
byte[] actual;
int bytesWritten;
// Too small
actual = new byte[cipherBytes.Length - 1];
Assert.False(rsa.TryEncrypt(TestData.HelloBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(0, bytesWritten);
// Just right
actual = new byte[cipherBytes.Length];
Assert.True(rsa.TryEncrypt(TestData.HelloBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(cipherBytes.Length, bytesWritten);
// Bigger than needed
actual = new byte[cipherBytes.Length + 1];
Assert.True(rsa.TryEncrypt(TestData.HelloBytes, actual, RSAEncryptionPadding.OaepSHA1, out bytesWritten));
Assert.Equal(cipherBytes.Length, bytesWritten);
}
}
[Fact]
public void Decrypt_WrongKey_Pkcs7()
{
Decrypt_WrongKey(RSAEncryptionPadding.Pkcs1);
}
[Fact]
public void Decrypt_WrongKey_OAEP_SHA1()
{
Decrypt_WrongKey(RSAEncryptionPadding.OaepSHA1);
}
[ConditionalFact(nameof(SupportsSha2Oaep))]
public void Decrypt_WrongKey_OAEP_SHA256()
{
Decrypt_WrongKey(RSAEncryptionPadding.OaepSHA256);
}
[Fact]
public static void EncryptDefaultSpan()
{
using (RSA rsa = RSAFactory.Create())
{
byte[] dest = new byte[rsa.KeySize / 8];
Assert.True(
rsa.TryEncrypt(ReadOnlySpan<byte>.Empty, dest, RSAEncryptionPadding.Pkcs1, out int written));
Assert.Equal(dest.Length, written);
Assert.True(
rsa.TryEncrypt(ReadOnlySpan<byte>.Empty, dest, RSAEncryptionPadding.OaepSHA1, out written));
Assert.Equal(dest.Length, written);
}
}
private static void Decrypt_WrongKey(RSAEncryptionPadding padding)
{
using (RSA rsa1 = RSAFactory.Create())
using (RSA rsa2 = RSAFactory.Create())
{
byte[] input = TestData.HelloBytes;
byte[] encrypted = rsa1.Encrypt(input, padding);
byte[] buf = new byte[encrypted.Length];
buf.AsSpan().Fill(0xCA);
int bytesWritten = 0;
// PKCS#1 padding allows for an incorrect response when the random key produces
// a start sequence of [ 00 02 !00 !00 !00 !00 !00 !00 !00 !00 ] with an eventual zero.
// 1/256 * 1/256 * (255/256)^8 is the start.
// 1 - (255/256)^(keySizeInBytes - 10) is the probability that there's an eventual zero.
// For RSA 2048, this works out to 9.142e-6, or 1 in 109385.
//
// OAEP is harder to reason about, it requires a bunch of data that hashes to a value
// that, XOR the remaining data, produces a value that is equivalent to a randomly
// generated number (which then runs through a formula and XORs back to "the input").
// The odds of that working are hard to say, but certainly much harder. Probably
// somewhere between 1 in 2^160 ("you made the right SHA-1 output") and 1 in 2^2048
// (you made the right private key). Since we already have the "if it succeeds, be wrong"
// code, just use it for OAEP, too.
try
{
// Because buf.Length >= ((rsa.KeySize / 8) - 11) (because it's rsa.KeySize / 8)
// false should never be returned.
//
// But if the padding doesn't work out (109384 out of 109385, see above) we'll throw.
bool decrypted = rsa2.TryDecrypt(encrypted, buf, padding, out bytesWritten);
Assert.True(decrypted, "Pkcs1 TryDecrypt succeeded with a large buffer");
// If bytesWritten != input.Length, we got back gibberish, which is good.
// If bytesWritten == input.Length then make sure at least one of the bytes is wrong.
// Probability time again.
// For RSA-2048, producing the input (ASCII("Hello")) requires a buffer of
// [ 00 02 248-nonzero-bytes 00 48 65 6C 6C 6F ]
// (1/256)^8 * (255/256)^248 = 3.2e-20, so this will fail 1 in 3.125e19 runs.
// One run a second => one failure every 990 billion years.
// (If our implementation is bad/weird, then all of these odds are meaningless, hence the test)
//
// For RSA-1024 (less freedom) it's 1 in 5.363e19, so like 1.6 trillion years.
if (rsa2.TryDecrypt(encrypted, buf, padding, out bytesWritten)
&& bytesWritten == input.Length)
{
// We'll get -here- 1 in 111014 runs (RSA-2048 Pkcs1).
Assert.NotEqual(input, buf.AsSpan(0, bytesWritten).ToArray());
}
}
catch (CryptographicException)
{
// 109384 out of 109385 times (RSA-2048 Pkcs1) we get here.
Assert.Equal(0, bytesWritten);
Assert.True(buf.All(b => b == 0xCA));
}
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/coreclr/pal/tests/palsuite/c_runtime/_snprintf_s/test15/test15.cpp | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test15.c
**
** Purpose: Tests sprintf_s with exponential format doubles (uppercase)
**
**
**==========================================================================*/
#include <palsuite.h>
#include "../_snprintf_s.h"
/*
* Notes: memcmp is used, as is strlen.
*/
PALTEST(c_runtime__snprintf_s_test15_paltest_snprintf_test15, "c_runtime/_snprintf_s/test15/paltest_snprintf_test15")
{
double val = 256.0;
double neg = -256.0;
if (PAL_Initialize(argc, argv) != 0)
{
return FAIL;
}
DoDoubleTest("foo %E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %lE", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %hE", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %LE", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %I64E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %14E", val, "foo 2.560000E+002",
"foo 2.560000E+02");
DoDoubleTest("foo %-14E", val, "foo 2.560000E+002 ",
"foo 2.560000E+02 ");
DoDoubleTest("foo %.1E", val, "foo 2.6E+002", "foo 2.6E+02");
DoDoubleTest("foo %.8E", val, "foo 2.56000000E+002",
"foo 2.56000000E+02");
DoDoubleTest("foo %014E", val, "foo 02.560000E+002",
"foo 002.560000E+02");
DoDoubleTest("foo %#E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %+E", val, "foo +2.560000E+002", "foo +2.560000E+02");
DoDoubleTest("foo % E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %+E", neg, "foo -2.560000E+002", "foo -2.560000E+02");
DoDoubleTest("foo % E", neg, "foo -2.560000E+002", "foo -2.560000E+02");
PAL_Terminate();
return PASS;
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test15.c
**
** Purpose: Tests sprintf_s with exponential format doubles (uppercase)
**
**
**==========================================================================*/
#include <palsuite.h>
#include "../_snprintf_s.h"
/*
* Notes: memcmp is used, as is strlen.
*/
PALTEST(c_runtime__snprintf_s_test15_paltest_snprintf_test15, "c_runtime/_snprintf_s/test15/paltest_snprintf_test15")
{
double val = 256.0;
double neg = -256.0;
if (PAL_Initialize(argc, argv) != 0)
{
return FAIL;
}
DoDoubleTest("foo %E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %lE", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %hE", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %LE", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %I64E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %14E", val, "foo 2.560000E+002",
"foo 2.560000E+02");
DoDoubleTest("foo %-14E", val, "foo 2.560000E+002 ",
"foo 2.560000E+02 ");
DoDoubleTest("foo %.1E", val, "foo 2.6E+002", "foo 2.6E+02");
DoDoubleTest("foo %.8E", val, "foo 2.56000000E+002",
"foo 2.56000000E+02");
DoDoubleTest("foo %014E", val, "foo 02.560000E+002",
"foo 002.560000E+02");
DoDoubleTest("foo %#E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %+E", val, "foo +2.560000E+002", "foo +2.560000E+02");
DoDoubleTest("foo % E", val, "foo 2.560000E+002", "foo 2.560000E+02");
DoDoubleTest("foo %+E", neg, "foo -2.560000E+002", "foo -2.560000E+02");
DoDoubleTest("foo % E", neg, "foo -2.560000E+002", "foo -2.560000E+02");
PAL_Terminate();
return PASS;
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.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.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
namespace System.Net
{
public sealed unsafe partial class HttpListenerRequest
{
private readonly ulong _requestId;
internal ulong _connectionId;
private readonly SslStatus _sslStatus;
private readonly string? _cookedUrlHost;
private readonly string? _cookedUrlPath;
private readonly string? _cookedUrlQuery;
private long _contentLength;
private Stream? _requestStream;
private string? _httpMethod;
private WebHeaderCollection? _webHeaders;
private IPEndPoint? _localEndPoint;
private IPEndPoint? _remoteEndPoint;
private BoundaryType _boundaryType;
private int _clientCertificateError;
private RequestContextBase? _memoryBlob;
private readonly HttpListenerContext _httpContext;
private bool _isDisposed;
internal const uint CertBoblSize = 1500;
private string? _serviceName;
private enum SslStatus : byte
{
Insecure,
NoClientCert,
ClientCert
}
internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(this, $"httpContext:${httpContext} memoryBlob {((IntPtr)memoryBlob.RequestBlob)}");
NetEventSource.Associate(this, httpContext);
}
_httpContext = httpContext;
_memoryBlob = memoryBlob;
_boundaryType = BoundaryType.None;
// Set up some of these now to avoid refcounting on memory blob later.
_requestId = memoryBlob.RequestBlob->RequestId;
_connectionId = memoryBlob.RequestBlob->ConnectionId;
_sslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure :
memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert :
SslStatus.ClientCert;
if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0)
{
_rawUrl = Marshal.PtrToStringAnsi((IntPtr)memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength);
}
Interop.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl;
if (cookedUrl.pHost != null && cookedUrl.HostLength > 0)
{
_cookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2);
}
if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0)
{
_cookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2);
}
if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0)
{
_cookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2);
}
_version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(this, $"RequestId:{RequestId} ConnectionId:{_connectionId} RawConnectionId:{memoryBlob.RequestBlob->RawConnectionId} UrlContext:{memoryBlob.RequestBlob->UrlContext} RawUrl:{_rawUrl} Version:{_version} Secure:{_sslStatus}");
NetEventSource.Info(this, $"httpContext:${httpContext} RequestUri:{RequestUri} Content-Length:{ContentLength64} HTTP Method:{HttpMethod}");
}
// Log headers
if (NetEventSource.Log.IsEnabled())
{
StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n");
for (int i = 0; i < Headers.Count; i++)
{
sb.Append('\t');
sb.Append(Headers.GetKey(i));
sb.Append(" : ");
sb.Append(Headers.Get(i));
sb.Append('\n');
}
NetEventSource.Info(this, sb.ToString());
}
}
internal HttpListenerContext HttpListenerContext => _httpContext;
// Note: RequestBuffer may get moved in memory. If you dereference a pointer from inside the RequestBuffer,
// you must use 'OriginalBlobAddress' below to adjust the location of the pointer to match the location of
// RequestBuffer.
internal IntPtr RequestBuffer
{
get
{
CheckDisposed();
return _memoryBlob!.RequestBuffer;
}
}
internal IntPtr OriginalBlobAddress
{
get
{
CheckDisposed();
return _memoryBlob!.OriginalBlobAddress;
}
}
// Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be
// disposed.
internal void DetachBlob(RequestContextBase memoryBlob)
{
if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob!)
{
_memoryBlob = null;
}
}
// Finalizes ownership of the memory blob. DetachBlob can't be called after this.
internal void ReleasePins()
{
_memoryBlob!.ReleasePins();
}
internal ulong RequestId => _requestId;
public Guid RequestTraceIdentifier
{
get
{
Guid guid = default;
*(1 + (ulong*)&guid) = RequestId;
return guid;
}
}
public long ContentLength64
{
get
{
if (_boundaryType == BoundaryType.None)
{
string? transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding];
if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase))
{
_boundaryType = BoundaryType.Chunked;
_contentLength = -1;
}
else
{
_contentLength = 0;
_boundaryType = BoundaryType.ContentLength;
string? length = Headers[HttpKnownHeaderNames.ContentLength];
if (length != null)
{
bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength);
if (!success)
{
_contentLength = 0;
_boundaryType = BoundaryType.Invalid;
}
}
}
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_contentLength:{_contentLength} _boundaryType:{_boundaryType}");
return _contentLength;
}
}
public NameValueCollection Headers
{
get
{
if (_webHeaders == null)
{
_webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"webHeaders:{_webHeaders}");
return _webHeaders;
}
}
public string HttpMethod
{
get
{
if (_httpMethod == null)
{
_httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}");
return _httpMethod!;
}
}
public Stream InputStream
{
get
{
if (_requestStream == null)
{
_requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
}
return _requestStream;
}
}
public bool IsAuthenticated
{
get
{
IPrincipal? user = HttpListenerContext.User;
return user != null && user.Identity != null && user.Identity.IsAuthenticated;
}
}
public bool IsSecureConnection => _sslStatus != SslStatus.Insecure;
public string? ServiceName
{
get => _serviceName;
internal set => _serviceName = value;
}
private int GetClientCertificateErrorCore()
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ClientCertificateError:{_clientCertificateError}");
return _clientCertificateError;
}
internal void SetClientCertificateError(int clientCertificateError)
{
_clientCertificateError = clientCertificateError;
}
public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult!!)
{
X509Certificate2? clientCertificate = null;
ListenerClientCertAsyncResult? clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (clientCertAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
}
clientCertAsyncResult.EndCalled = true;
clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
return clientCertificate;
}
public TransportContext TransportContext => new HttpListenerRequestContext(this);
public bool HasEntityBody
{
get
{
// accessing the ContentLength property delay creates m_BoundaryType
return (ContentLength64 > 0 && _boundaryType == BoundaryType.ContentLength) ||
_boundaryType == BoundaryType.Chunked || _boundaryType == BoundaryType.Multipart;
}
}
public IPEndPoint RemoteEndPoint
{
get
{
if (_remoteEndPoint == null)
{
_remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint);
return _remoteEndPoint!;
}
}
public IPEndPoint LocalEndPoint
{
get
{
if (_localEndPoint == null)
{
_localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}");
return _localEndPoint!;
}
}
//should only be called from httplistenercontext
internal void Close()
{
RequestContextBase? memoryBlob = _memoryBlob;
if (memoryBlob != null)
{
memoryBlob.Close();
_memoryBlob = null;
}
_isDisposed = true;
}
private ListenerClientCertAsyncResult BeginGetClientCertificateCore(AsyncCallback? requestCallback, object? state)
{
ListenerClientCertAsyncResult? asyncResult = null;
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are required at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, size);
try
{
while (true)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
asyncResult.RequestBlob,
size,
&bytesReceived,
asyncResult.NativeOverlapped);
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
size = bytesReceived + pClientCertInfo->CertEncodedSize;
asyncResult.Reset(size);
continue;
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
// someother bad error, possible return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
// Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required.
throw new HttpListenerException((int)statusCode);
}
if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
asyncResult.IOCompleted(statusCode, bytesReceived);
}
break;
}
}
catch
{
asyncResult?.InternalCleanup();
throw;
}
}
else
{
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, 0);
asyncResult.InvokeCallback();
}
return asyncResult;
}
private void GetClientCertificateCore()
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this);
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are required at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
while (true)
{
byte[] clientCertInfoBlob = new byte[checked((int)size)];
fixed (byte* pClientCertInfoBlob = &clientCertInfoBlob[0])
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)pClientCertInfoBlob;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
pClientCertInfo,
size,
&bytesReceived,
null);
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
size = bytesReceived + pClientCertInfo->CertEncodedSize;
continue;
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS)
{
if (pClientCertInfo != null)
{
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(this, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}");
if (pClientCertInfo->pCertEncoded != null)
{
try
{
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
ClientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"CryptographicException={exception}");
}
catch (SecurityException exception)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"SecurityException={exception}");
}
}
_clientCertificateError = (int)pClientCertInfo->CertFlags;
}
}
else
{
Debug.Assert(statusCode == Interop.HttpApi.ERROR_NOT_FOUND,
$"Call to Interop.HttpApi.HttpReceiveClientCertificate() failed with statusCode {statusCode}.");
}
}
break;
}
}
}
private Uri RequestUri
{
get
{
if (_requestUri == null)
{
_requestUri = HttpListenerRequestUriBuilder.GetRequestUri(
_rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_requestUri:{_requestUri}");
return _requestUri;
}
}
internal ChannelBinding? GetChannelBinding()
{
return HttpListener.GetChannelBindingFromTls(HttpListenerContext.ListenerSession, _connectionId);
}
internal void CheckDisposed()
{
ObjectDisposedException.ThrowIf(_isDisposed, this);
}
private bool SupportsWebSockets => WebSocketProtocolComponent.IsSupported;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
namespace System.Net
{
public sealed unsafe partial class HttpListenerRequest
{
private readonly ulong _requestId;
internal ulong _connectionId;
private readonly SslStatus _sslStatus;
private readonly string? _cookedUrlHost;
private readonly string? _cookedUrlPath;
private readonly string? _cookedUrlQuery;
private long _contentLength;
private Stream? _requestStream;
private string? _httpMethod;
private WebHeaderCollection? _webHeaders;
private IPEndPoint? _localEndPoint;
private IPEndPoint? _remoteEndPoint;
private BoundaryType _boundaryType;
private int _clientCertificateError;
private RequestContextBase? _memoryBlob;
private readonly HttpListenerContext _httpContext;
private bool _isDisposed;
internal const uint CertBoblSize = 1500;
private string? _serviceName;
private enum SslStatus : byte
{
Insecure,
NoClientCert,
ClientCert
}
internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(this, $"httpContext:${httpContext} memoryBlob {((IntPtr)memoryBlob.RequestBlob)}");
NetEventSource.Associate(this, httpContext);
}
_httpContext = httpContext;
_memoryBlob = memoryBlob;
_boundaryType = BoundaryType.None;
// Set up some of these now to avoid refcounting on memory blob later.
_requestId = memoryBlob.RequestBlob->RequestId;
_connectionId = memoryBlob.RequestBlob->ConnectionId;
_sslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure :
memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert :
SslStatus.ClientCert;
if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0)
{
_rawUrl = Marshal.PtrToStringAnsi((IntPtr)memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength);
}
Interop.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl;
if (cookedUrl.pHost != null && cookedUrl.HostLength > 0)
{
_cookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2);
}
if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0)
{
_cookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2);
}
if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0)
{
_cookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2);
}
_version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(this, $"RequestId:{RequestId} ConnectionId:{_connectionId} RawConnectionId:{memoryBlob.RequestBlob->RawConnectionId} UrlContext:{memoryBlob.RequestBlob->UrlContext} RawUrl:{_rawUrl} Version:{_version} Secure:{_sslStatus}");
NetEventSource.Info(this, $"httpContext:${httpContext} RequestUri:{RequestUri} Content-Length:{ContentLength64} HTTP Method:{HttpMethod}");
}
// Log headers
if (NetEventSource.Log.IsEnabled())
{
StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n");
for (int i = 0; i < Headers.Count; i++)
{
sb.Append('\t');
sb.Append(Headers.GetKey(i));
sb.Append(" : ");
sb.Append(Headers.Get(i));
sb.Append('\n');
}
NetEventSource.Info(this, sb.ToString());
}
}
internal HttpListenerContext HttpListenerContext => _httpContext;
// Note: RequestBuffer may get moved in memory. If you dereference a pointer from inside the RequestBuffer,
// you must use 'OriginalBlobAddress' below to adjust the location of the pointer to match the location of
// RequestBuffer.
internal IntPtr RequestBuffer
{
get
{
CheckDisposed();
return _memoryBlob!.RequestBuffer;
}
}
internal IntPtr OriginalBlobAddress
{
get
{
CheckDisposed();
return _memoryBlob!.OriginalBlobAddress;
}
}
// Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be
// disposed.
internal void DetachBlob(RequestContextBase memoryBlob)
{
if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob!)
{
_memoryBlob = null;
}
}
// Finalizes ownership of the memory blob. DetachBlob can't be called after this.
internal void ReleasePins()
{
_memoryBlob!.ReleasePins();
}
internal ulong RequestId => _requestId;
public Guid RequestTraceIdentifier
{
get
{
Guid guid = default;
*(1 + (ulong*)&guid) = RequestId;
return guid;
}
}
public long ContentLength64
{
get
{
if (_boundaryType == BoundaryType.None)
{
string? transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding];
if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase))
{
_boundaryType = BoundaryType.Chunked;
_contentLength = -1;
}
else
{
_contentLength = 0;
_boundaryType = BoundaryType.ContentLength;
string? length = Headers[HttpKnownHeaderNames.ContentLength];
if (length != null)
{
bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength);
if (!success)
{
_contentLength = 0;
_boundaryType = BoundaryType.Invalid;
}
}
}
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_contentLength:{_contentLength} _boundaryType:{_boundaryType}");
return _contentLength;
}
}
public NameValueCollection Headers
{
get
{
if (_webHeaders == null)
{
_webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"webHeaders:{_webHeaders}");
return _webHeaders;
}
}
public string HttpMethod
{
get
{
if (_httpMethod == null)
{
_httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}");
return _httpMethod!;
}
}
public Stream InputStream
{
get
{
if (_requestStream == null)
{
_requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
}
return _requestStream;
}
}
public bool IsAuthenticated
{
get
{
IPrincipal? user = HttpListenerContext.User;
return user != null && user.Identity != null && user.Identity.IsAuthenticated;
}
}
public bool IsSecureConnection => _sslStatus != SslStatus.Insecure;
public string? ServiceName
{
get => _serviceName;
internal set => _serviceName = value;
}
private int GetClientCertificateErrorCore()
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ClientCertificateError:{_clientCertificateError}");
return _clientCertificateError;
}
internal void SetClientCertificateError(int clientCertificateError)
{
_clientCertificateError = clientCertificateError;
}
public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult!!)
{
X509Certificate2? clientCertificate = null;
ListenerClientCertAsyncResult? clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (clientCertAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
}
clientCertAsyncResult.EndCalled = true;
clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_clientCertificate:{ClientCertificate}");
return clientCertificate;
}
public TransportContext TransportContext => new HttpListenerRequestContext(this);
public bool HasEntityBody
{
get
{
// accessing the ContentLength property delay creates m_BoundaryType
return (ContentLength64 > 0 && _boundaryType == BoundaryType.ContentLength) ||
_boundaryType == BoundaryType.Chunked || _boundaryType == BoundaryType.Multipart;
}
}
public IPEndPoint RemoteEndPoint
{
get
{
if (_remoteEndPoint == null)
{
_remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint);
return _remoteEndPoint!;
}
}
public IPEndPoint LocalEndPoint
{
get
{
if (_localEndPoint == null)
{
_localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}");
return _localEndPoint!;
}
}
//should only be called from httplistenercontext
internal void Close()
{
RequestContextBase? memoryBlob = _memoryBlob;
if (memoryBlob != null)
{
memoryBlob.Close();
_memoryBlob = null;
}
_isDisposed = true;
}
private ListenerClientCertAsyncResult BeginGetClientCertificateCore(AsyncCallback? requestCallback, object? state)
{
ListenerClientCertAsyncResult? asyncResult = null;
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are required at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, size);
try
{
while (true)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
asyncResult.RequestBlob,
size,
&bytesReceived,
asyncResult.NativeOverlapped);
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
size = bytesReceived + pClientCertInfo->CertEncodedSize;
asyncResult.Reset(size);
continue;
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
// someother bad error, possible return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
// Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required.
throw new HttpListenerException((int)statusCode);
}
if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
asyncResult.IOCompleted(statusCode, bytesReceived);
}
break;
}
}
catch
{
asyncResult?.InternalCleanup();
throw;
}
}
else
{
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, 0);
asyncResult.InvokeCallback();
}
return asyncResult;
}
private void GetClientCertificateCore()
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this);
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are required at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
while (true)
{
byte[] clientCertInfoBlob = new byte[checked((int)size)];
fixed (byte* pClientCertInfoBlob = &clientCertInfoBlob[0])
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)pClientCertInfoBlob;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
pClientCertInfo,
size,
&bytesReceived,
null);
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
size = bytesReceived + pClientCertInfo->CertEncodedSize;
continue;
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS)
{
if (pClientCertInfo != null)
{
if (NetEventSource.Log.IsEnabled())
NetEventSource.Info(this, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}");
if (pClientCertInfo->pCertEncoded != null)
{
try
{
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
ClientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"CryptographicException={exception}");
}
catch (SecurityException exception)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"SecurityException={exception}");
}
}
_clientCertificateError = (int)pClientCertInfo->CertFlags;
}
}
else
{
Debug.Assert(statusCode == Interop.HttpApi.ERROR_NOT_FOUND,
$"Call to Interop.HttpApi.HttpReceiveClientCertificate() failed with statusCode {statusCode}.");
}
}
break;
}
}
}
private Uri RequestUri
{
get
{
if (_requestUri == null)
{
_requestUri = HttpListenerRequestUriBuilder.GetRequestUri(
_rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!);
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_requestUri:{_requestUri}");
return _requestUri;
}
}
internal ChannelBinding? GetChannelBinding()
{
return HttpListener.GetChannelBindingFromTls(HttpListenerContext.ListenerSession, _connectionId);
}
internal void CheckDisposed()
{
ObjectDisposedException.ThrowIf(_isDisposed, this);
}
private bool SupportsWebSockets => WebSocketProtocolComponent.IsSupported;
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Memory/tests/ParsersAndFormatters/SupportedFormats.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.Linq;
using System.Collections.Generic;
namespace System.Buffers.Text.Tests
{
// Test metadata that describes a standard format (e.g. 'G', 'D' and 'X') supported by a particular data type.
public sealed class SupportedFormat
{
public SupportedFormat(char symbol, bool supportsPrecision)
{
Symbol = symbol;
SupportsPrecision = supportsPrecision;
}
public char Symbol { get; }
public bool SupportsPrecision { get; }
public bool IsDefault { get; set; } = false;
public bool NoRepresentation { get; set; } = false; // If true, can only be accessed by passing default(StandardFormat). (The weird DateTimeOffset case.)
public char FormatSynonymFor { get; set; } = default;
public char ParseSynonymFor { get; set; } = default;
}
internal static partial class TestData
{
public static bool IsParsingImplemented<T>(this SupportedFormat f) => f.IsParsingImplemented(typeof(T));
//
// Used to disable automatic generation of ParserTestData from FormatterTestData. Useful for bringing up new
// formats as you can use this shutoff valve to bring up formatting without having to bring up parsing at the same time.
//
public static bool IsParsingImplemented(this SupportedFormat f, Type t)
{
return true;
}
public static IEnumerable<SupportedFormat> IntegerFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('g', supportsPrecision: false) { FormatSynonymFor = 'G', ParseSynonymFor = 'G' };
yield return new SupportedFormat('D', supportsPrecision: true);
yield return new SupportedFormat('d', supportsPrecision: true) { FormatSynonymFor = 'D', ParseSynonymFor = 'd' };
yield return new SupportedFormat('N', supportsPrecision: true);
yield return new SupportedFormat('n', supportsPrecision: true) { FormatSynonymFor = 'N', ParseSynonymFor = 'N' };
yield return new SupportedFormat('X', supportsPrecision: true);
yield return new SupportedFormat('x', supportsPrecision: true) { ParseSynonymFor = 'X' };
}
}
public static IEnumerable<SupportedFormat> DecimalFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('g', supportsPrecision: false) { FormatSynonymFor = 'G', ParseSynonymFor = 'G' };
yield return new SupportedFormat('E', supportsPrecision: true);
yield return new SupportedFormat('e', supportsPrecision: true) { ParseSynonymFor = 'E' };
yield return new SupportedFormat('F', supportsPrecision: true);
yield return new SupportedFormat('f', supportsPrecision: true) { FormatSynonymFor = 'F', ParseSynonymFor = 'F' };
}
}
public static IEnumerable<SupportedFormat> FloatingPointFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('g', supportsPrecision: false) { FormatSynonymFor = 'G', ParseSynonymFor = 'G' };
yield return new SupportedFormat('E', supportsPrecision: true);
yield return new SupportedFormat('e', supportsPrecision: true) { ParseSynonymFor = 'E' };
yield return new SupportedFormat('F', supportsPrecision: true);
yield return new SupportedFormat('f', supportsPrecision: true) { FormatSynonymFor = 'F', ParseSynonymFor = 'F' };
}
}
public static IEnumerable<SupportedFormat> BooleanFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('l', supportsPrecision: false) { ParseSynonymFor = 'l' };
}
}
public static IEnumerable<SupportedFormat> GuidFormats
{
get
{
yield return new SupportedFormat('D', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('N', supportsPrecision: false);
yield return new SupportedFormat('P', supportsPrecision: false);
yield return new SupportedFormat('B', supportsPrecision: false);
}
}
public static IEnumerable<SupportedFormat> DateTimeFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('R', supportsPrecision: false);
yield return new SupportedFormat('l', supportsPrecision: false);
yield return new SupportedFormat('O', supportsPrecision: false);
}
}
public static IEnumerable<SupportedFormat> DateTimeOffsetFormats
{
get
{
// The "default" format for DateTimeOffset is weird - it's like "G" but also suffixes an offset so it doesn't exactly match any of the explicit offsets.
yield return new SupportedFormat(default, supportsPrecision: false) { IsDefault = true, NoRepresentation = true };
yield return new SupportedFormat('G', supportsPrecision: false);
yield return new SupportedFormat('R', supportsPrecision: false);
yield return new SupportedFormat('l', supportsPrecision: false);
yield return new SupportedFormat('O', supportsPrecision: false);
}
}
public static IEnumerable<SupportedFormat> TimeSpanFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false);
yield return new SupportedFormat('g', supportsPrecision: false);
yield return new SupportedFormat('c', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('t', supportsPrecision: false) { ParseSynonymFor = 'c', FormatSynonymFor = 'c' };
yield return new SupportedFormat('T', supportsPrecision: false) { ParseSynonymFor = 'c', FormatSynonymFor = 'c' };
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using System.Collections.Generic;
namespace System.Buffers.Text.Tests
{
// Test metadata that describes a standard format (e.g. 'G', 'D' and 'X') supported by a particular data type.
public sealed class SupportedFormat
{
public SupportedFormat(char symbol, bool supportsPrecision)
{
Symbol = symbol;
SupportsPrecision = supportsPrecision;
}
public char Symbol { get; }
public bool SupportsPrecision { get; }
public bool IsDefault { get; set; } = false;
public bool NoRepresentation { get; set; } = false; // If true, can only be accessed by passing default(StandardFormat). (The weird DateTimeOffset case.)
public char FormatSynonymFor { get; set; } = default;
public char ParseSynonymFor { get; set; } = default;
}
internal static partial class TestData
{
public static bool IsParsingImplemented<T>(this SupportedFormat f) => f.IsParsingImplemented(typeof(T));
//
// Used to disable automatic generation of ParserTestData from FormatterTestData. Useful for bringing up new
// formats as you can use this shutoff valve to bring up formatting without having to bring up parsing at the same time.
//
public static bool IsParsingImplemented(this SupportedFormat f, Type t)
{
return true;
}
public static IEnumerable<SupportedFormat> IntegerFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('g', supportsPrecision: false) { FormatSynonymFor = 'G', ParseSynonymFor = 'G' };
yield return new SupportedFormat('D', supportsPrecision: true);
yield return new SupportedFormat('d', supportsPrecision: true) { FormatSynonymFor = 'D', ParseSynonymFor = 'd' };
yield return new SupportedFormat('N', supportsPrecision: true);
yield return new SupportedFormat('n', supportsPrecision: true) { FormatSynonymFor = 'N', ParseSynonymFor = 'N' };
yield return new SupportedFormat('X', supportsPrecision: true);
yield return new SupportedFormat('x', supportsPrecision: true) { ParseSynonymFor = 'X' };
}
}
public static IEnumerable<SupportedFormat> DecimalFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('g', supportsPrecision: false) { FormatSynonymFor = 'G', ParseSynonymFor = 'G' };
yield return new SupportedFormat('E', supportsPrecision: true);
yield return new SupportedFormat('e', supportsPrecision: true) { ParseSynonymFor = 'E' };
yield return new SupportedFormat('F', supportsPrecision: true);
yield return new SupportedFormat('f', supportsPrecision: true) { FormatSynonymFor = 'F', ParseSynonymFor = 'F' };
}
}
public static IEnumerable<SupportedFormat> FloatingPointFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('g', supportsPrecision: false) { FormatSynonymFor = 'G', ParseSynonymFor = 'G' };
yield return new SupportedFormat('E', supportsPrecision: true);
yield return new SupportedFormat('e', supportsPrecision: true) { ParseSynonymFor = 'E' };
yield return new SupportedFormat('F', supportsPrecision: true);
yield return new SupportedFormat('f', supportsPrecision: true) { FormatSynonymFor = 'F', ParseSynonymFor = 'F' };
}
}
public static IEnumerable<SupportedFormat> BooleanFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('l', supportsPrecision: false) { ParseSynonymFor = 'l' };
}
}
public static IEnumerable<SupportedFormat> GuidFormats
{
get
{
yield return new SupportedFormat('D', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('N', supportsPrecision: false);
yield return new SupportedFormat('P', supportsPrecision: false);
yield return new SupportedFormat('B', supportsPrecision: false);
}
}
public static IEnumerable<SupportedFormat> DateTimeFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('R', supportsPrecision: false);
yield return new SupportedFormat('l', supportsPrecision: false);
yield return new SupportedFormat('O', supportsPrecision: false);
}
}
public static IEnumerable<SupportedFormat> DateTimeOffsetFormats
{
get
{
// The "default" format for DateTimeOffset is weird - it's like "G" but also suffixes an offset so it doesn't exactly match any of the explicit offsets.
yield return new SupportedFormat(default, supportsPrecision: false) { IsDefault = true, NoRepresentation = true };
yield return new SupportedFormat('G', supportsPrecision: false);
yield return new SupportedFormat('R', supportsPrecision: false);
yield return new SupportedFormat('l', supportsPrecision: false);
yield return new SupportedFormat('O', supportsPrecision: false);
}
}
public static IEnumerable<SupportedFormat> TimeSpanFormats
{
get
{
yield return new SupportedFormat('G', supportsPrecision: false);
yield return new SupportedFormat('g', supportsPrecision: false);
yield return new SupportedFormat('c', supportsPrecision: false) { IsDefault = true };
yield return new SupportedFormat('t', supportsPrecision: false) { ParseSynonymFor = 'c', FormatSynonymFor = 'c' };
yield return new SupportedFormat('T', supportsPrecision: false) { ParseSynonymFor = 'c', FormatSynonymFor = 'c' };
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/BackgroundWorker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.ComponentModel
{
public class BackgroundWorker : Component
{
// Private instance members
private bool _canCancelWorker;
private bool _workerReportsProgress;
private bool _cancellationPending;
private bool _isRunning;
private AsyncOperation? _asyncOperation;
private readonly SendOrPostCallback _operationCompleted;
private readonly SendOrPostCallback _progressReporter;
public BackgroundWorker()
{
_operationCompleted = new SendOrPostCallback(AsyncOperationCompleted!);
_progressReporter = new SendOrPostCallback(ProgressReporter!);
}
private void AsyncOperationCompleted(object arg)
{
_isRunning = false;
_cancellationPending = false;
OnRunWorkerCompleted((RunWorkerCompletedEventArgs)arg);
}
public bool CancellationPending
{
get
{
return _cancellationPending;
}
}
public void CancelAsync()
{
if (!WorkerSupportsCancellation)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntSupportCancellation);
}
_cancellationPending = true;
}
public event DoWorkEventHandler? DoWork;
public bool IsBusy
{
get
{
return _isRunning;
}
}
protected virtual void OnDoWork(DoWorkEventArgs e)
{
DoWork?.Invoke(this, e);
}
protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
RunWorkerCompleted?.Invoke(this, e);
}
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
ProgressChanged?.Invoke(this, e);
}
public event ProgressChangedEventHandler? ProgressChanged;
// Gets invoked through the AsyncOperation on the proper thread.
private void ProgressReporter(object arg)
{
OnProgressChanged((ProgressChangedEventArgs)arg);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress)
{
ReportProgress(percentProgress, null);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress, object? userState)
{
if (!WorkerReportsProgress)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntReportProgress);
}
ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentProgress, userState);
if (_asyncOperation != null)
{
_asyncOperation.Post(_progressReporter, args);
}
else
{
_progressReporter(args);
}
}
public void RunWorkerAsync()
{
RunWorkerAsync(null);
}
public void RunWorkerAsync(object? argument)
{
if (_isRunning)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerAlreadyRunning);
}
_isRunning = true;
_cancellationPending = false;
_asyncOperation = AsyncOperationManager.CreateOperation(null);
Task.Factory.StartNew(
arg => WorkerThreadStart(arg),
argument,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default
);
}
public event RunWorkerCompletedEventHandler? RunWorkerCompleted;
public bool WorkerReportsProgress
{
get
{
return _workerReportsProgress;
}
set
{
_workerReportsProgress = value;
}
}
public bool WorkerSupportsCancellation
{
get
{
return _canCancelWorker;
}
set
{
_canCancelWorker = value;
}
}
private void WorkerThreadStart(object? argument)
{
Debug.Assert(_asyncOperation != null, "_asyncOperation not initialized");
object? workerResult = null;
Exception? error = null;
bool cancelled = false;
try
{
DoWorkEventArgs doWorkArgs = new DoWorkEventArgs(argument);
OnDoWork(doWorkArgs);
if (doWorkArgs.Cancel)
{
cancelled = true;
}
else
{
workerResult = doWorkArgs.Result;
}
}
catch (Exception exception)
{
error = exception;
}
var e = new RunWorkerCompletedEventArgs(workerResult, error, cancelled);
_asyncOperation.PostOperationCompleted(_operationCompleted, e);
}
protected override void Dispose(bool disposing)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.ComponentModel
{
public class BackgroundWorker : Component
{
// Private instance members
private bool _canCancelWorker;
private bool _workerReportsProgress;
private bool _cancellationPending;
private bool _isRunning;
private AsyncOperation? _asyncOperation;
private readonly SendOrPostCallback _operationCompleted;
private readonly SendOrPostCallback _progressReporter;
public BackgroundWorker()
{
_operationCompleted = new SendOrPostCallback(AsyncOperationCompleted!);
_progressReporter = new SendOrPostCallback(ProgressReporter!);
}
private void AsyncOperationCompleted(object arg)
{
_isRunning = false;
_cancellationPending = false;
OnRunWorkerCompleted((RunWorkerCompletedEventArgs)arg);
}
public bool CancellationPending
{
get
{
return _cancellationPending;
}
}
public void CancelAsync()
{
if (!WorkerSupportsCancellation)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntSupportCancellation);
}
_cancellationPending = true;
}
public event DoWorkEventHandler? DoWork;
public bool IsBusy
{
get
{
return _isRunning;
}
}
protected virtual void OnDoWork(DoWorkEventArgs e)
{
DoWork?.Invoke(this, e);
}
protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
RunWorkerCompleted?.Invoke(this, e);
}
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
ProgressChanged?.Invoke(this, e);
}
public event ProgressChangedEventHandler? ProgressChanged;
// Gets invoked through the AsyncOperation on the proper thread.
private void ProgressReporter(object arg)
{
OnProgressChanged((ProgressChangedEventArgs)arg);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress)
{
ReportProgress(percentProgress, null);
}
// Cause progress update to be posted through current AsyncOperation.
public void ReportProgress(int percentProgress, object? userState)
{
if (!WorkerReportsProgress)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntReportProgress);
}
ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentProgress, userState);
if (_asyncOperation != null)
{
_asyncOperation.Post(_progressReporter, args);
}
else
{
_progressReporter(args);
}
}
public void RunWorkerAsync()
{
RunWorkerAsync(null);
}
public void RunWorkerAsync(object? argument)
{
if (_isRunning)
{
throw new InvalidOperationException(SR.BackgroundWorker_WorkerAlreadyRunning);
}
_isRunning = true;
_cancellationPending = false;
_asyncOperation = AsyncOperationManager.CreateOperation(null);
Task.Factory.StartNew(
arg => WorkerThreadStart(arg),
argument,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default
);
}
public event RunWorkerCompletedEventHandler? RunWorkerCompleted;
public bool WorkerReportsProgress
{
get
{
return _workerReportsProgress;
}
set
{
_workerReportsProgress = value;
}
}
public bool WorkerSupportsCancellation
{
get
{
return _canCancelWorker;
}
set
{
_canCancelWorker = value;
}
}
private void WorkerThreadStart(object? argument)
{
Debug.Assert(_asyncOperation != null, "_asyncOperation not initialized");
object? workerResult = null;
Exception? error = null;
bool cancelled = false;
try
{
DoWorkEventArgs doWorkArgs = new DoWorkEventArgs(argument);
OnDoWork(doWorkArgs);
if (doWorkArgs.Cancel)
{
cancelled = true;
}
else
{
workerResult = doWorkArgs.Result;
}
}
catch (Exception exception)
{
error = exception;
}
var e = new RunWorkerCompletedEventArgs(workerResult, error, cancelled);
_asyncOperation.PostOperationCompleted(_operationCompleted, e);
}
protected override void Dispose(bool disposing)
{
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/coreclr/tools/aot/ILCompiler.ReadyToRun/ObjectWriter/OutputInfoBuilder.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.CodeAnalysis;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Internal.JitInterface;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysis.ReadyToRun;
using ILCompiler.Diagnostics;
namespace ILCompiler.PEWriter
{
/// <summary>
/// Base class for symbols and nodes in the output file implements common logic
/// for section / offset ordering.
/// </summary>
public class OutputItem
{
public class Comparer : IComparer<OutputItem>
{
public readonly static Comparer Instance = new Comparer();
public int Compare([AllowNull] OutputItem x, [AllowNull] OutputItem y)
{
return (x.SectionIndex != y.SectionIndex ? x.SectionIndex.CompareTo(y.SectionIndex) : x.Offset.CompareTo(y.Offset));
}
}
/// <summary>
/// Item section index
/// </summary>
public readonly int SectionIndex;
/// <summary>
/// Offset relative to section beginning
/// </summary>
public readonly int Offset;
/// <summary>
/// Item name
/// </summary>
public readonly string Name;
public OutputItem(int sectionIndex, int offset, string name)
{
SectionIndex = sectionIndex;
Offset = offset;
Name = name;
}
}
/// <summary>
/// This class represents a single node (contiguous block of data) in the output R2R PE file.
/// </summary>
public class OutputNode : OutputItem
{
/// <summary>
/// Node length (number of bytes). This doesn't include any external alignment
/// applied when concatenating the nodes to form sections.
/// </summary>
public readonly int Length;
/// <summary>
/// Number of file-level relocations (.reloc section entries) used by the node.
/// </summary>
public int Relocations { get; private set; }
public OutputNode(int sectionIndex, int offset, int length, string name)
: base(sectionIndex, offset, name)
{
Length = length;
Relocations = 0;
}
public void AddRelocation()
{
Relocations++;
}
}
/// <summary>
/// Symbol is a "pointer" into the PE file. Most (but not all) symbols correspond to
/// node beginnings (most nodes have a "start symbol" representing the beginning
/// of the node).
/// </summary>
public class OutputSymbol : OutputItem
{
public OutputSymbol(int sectionIndex, int offset, string name)
: base(sectionIndex, offset, name)
{
}
}
/// <summary>
/// Common class used to collect information to use when emitting map files and symbol files.
/// </summary>
public class OutputInfoBuilder
{
private readonly List<EcmaModule> _inputModules;
private readonly List<OutputNode> _nodes;
private readonly List<OutputSymbol> _symbols;
private readonly List<Section> _sections;
private readonly Dictionary<ISymbolDefinitionNode, OutputNode> _nodeSymbolMap;
private readonly Dictionary<ISymbolDefinitionNode, MethodWithGCInfo> _methodSymbolMap;
private readonly Dictionary<RelocType, int> _relocCounts;
public OutputInfoBuilder()
{
_inputModules = new List<EcmaModule>();
_nodes = new List<OutputNode>();
_symbols = new List<OutputSymbol>();
_sections = new List<Section>();
_nodeSymbolMap = new Dictionary<ISymbolDefinitionNode, OutputNode>();
_methodSymbolMap = new Dictionary<ISymbolDefinitionNode, MethodWithGCInfo>();
_relocCounts = new Dictionary<RelocType, int>();
}
public void AddInputModule(EcmaModule module)
{
_inputModules.Add(module);
}
public void AddNode(OutputNode node, ISymbolDefinitionNode symbol)
{
_nodes.Add(node);
_nodeSymbolMap.Add(symbol, node);
}
public void AddRelocation(OutputNode node, RelocType relocType)
{
node.AddRelocation();
_relocCounts.TryGetValue(relocType, out int relocTypeCount);
_relocCounts[relocType] = relocTypeCount + 1;
}
public void AddSymbol(OutputSymbol symbol)
{
_symbols.Add(symbol);
}
public void AddSection(Section section)
{
_sections.Add(section);
}
public void AddMethod(MethodWithGCInfo method, ISymbolDefinitionNode symbol)
{
_methodSymbolMap.Add(symbol, method);
}
public void Sort()
{
_nodes.Sort(OutputItem.Comparer.Instance);
_symbols.Sort(OutputItem.Comparer.Instance);
}
public bool FindSymbol(OutputItem item, out int index)
{
index = _symbols.BinarySearch(new OutputSymbol(item.SectionIndex, item.Offset, name: null), OutputItem.Comparer.Instance);
bool result = (index >= 0 && index < _symbols.Count && OutputItem.Comparer.Instance.Compare(_symbols[index], item) == 0);
if (!result)
{
index = -1;
}
return result;
}
public IEnumerable<MethodInfo> EnumerateMethods()
{
DebugNameFormatter nameFormatter = new DebugNameFormatter();
TypeNameFormatter typeNameFormatter = new TypeString();
HashSet<MethodDesc> emittedMethods = new HashSet<MethodDesc>();
foreach (KeyValuePair<ISymbolDefinitionNode, MethodWithGCInfo> symbolMethodPair in _methodSymbolMap)
{
EcmaMethod ecmaMethod = symbolMethodPair.Value.Method.GetTypicalMethodDefinition() as EcmaMethod;
if (ecmaMethod != null && emittedMethods.Add(ecmaMethod))
{
MethodInfo methodInfo = new MethodInfo();
methodInfo.MethodToken = (uint)MetadataTokens.GetToken(ecmaMethod.Handle);
methodInfo.AssemblyName = ecmaMethod.Module.Assembly.GetName().Name;
methodInfo.Name = FormatMethodName(symbolMethodPair.Value.Method, typeNameFormatter);
OutputNode node = _nodeSymbolMap[symbolMethodPair.Key];
Section section = _sections[node.SectionIndex];
methodInfo.HotRVA = (uint)(section.RVAWhenPlaced + node.Offset);
methodInfo.HotLength = (uint)node.Length;
methodInfo.ColdRVA = 0;
methodInfo.ColdLength = 0;
yield return methodInfo;
}
}
}
public IEnumerable<AssemblyInfo> EnumerateInputAssemblies()
{
foreach (EcmaModule inputModule in _inputModules)
{
yield return new AssemblyInfo(
inputModule.Assembly.GetName().Name,
inputModule.MetadataReader.GetGuid(inputModule.MetadataReader.GetModuleDefinition().Mvid));
}
}
private string FormatMethodName(MethodDesc method, TypeNameFormatter typeNameFormatter)
{
StringBuilder output = new StringBuilder();
if (!method.Signature.ReturnType.IsVoid)
{
output.Append(typeNameFormatter.FormatName(method.Signature.ReturnType));
output.Append(" ");
}
output.Append(typeNameFormatter.FormatName(method.OwningType));
output.Append("::");
output.Append(method.Name);
output.Append("(");
for (int paramIndex = 0; paramIndex < method.Signature.Length; paramIndex++)
{
if (paramIndex != 0)
{
output.Append(", ");
}
output.Append(typeNameFormatter.FormatName(method.Signature[paramIndex]));
}
output.Append(")");
return output.ToString();
}
public IReadOnlyList<OutputNode> Nodes => _nodes;
public IReadOnlyList<Section> Sections => _sections;
public IReadOnlyList<OutputSymbol> Symbols => _symbols;
public IReadOnlyDictionary<ISymbolDefinitionNode, OutputNode> NodeSymbolMap => _nodeSymbolMap;
public IReadOnlyDictionary<ISymbolDefinitionNode, MethodWithGCInfo> MethodSymbolMap => _methodSymbolMap;
public IReadOnlyDictionary<RelocType, int> RelocCounts => _relocCounts;
}
}
| // 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.CodeAnalysis;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Internal.JitInterface;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysis.ReadyToRun;
using ILCompiler.Diagnostics;
namespace ILCompiler.PEWriter
{
/// <summary>
/// Base class for symbols and nodes in the output file implements common logic
/// for section / offset ordering.
/// </summary>
public class OutputItem
{
public class Comparer : IComparer<OutputItem>
{
public readonly static Comparer Instance = new Comparer();
public int Compare([AllowNull] OutputItem x, [AllowNull] OutputItem y)
{
return (x.SectionIndex != y.SectionIndex ? x.SectionIndex.CompareTo(y.SectionIndex) : x.Offset.CompareTo(y.Offset));
}
}
/// <summary>
/// Item section index
/// </summary>
public readonly int SectionIndex;
/// <summary>
/// Offset relative to section beginning
/// </summary>
public readonly int Offset;
/// <summary>
/// Item name
/// </summary>
public readonly string Name;
public OutputItem(int sectionIndex, int offset, string name)
{
SectionIndex = sectionIndex;
Offset = offset;
Name = name;
}
}
/// <summary>
/// This class represents a single node (contiguous block of data) in the output R2R PE file.
/// </summary>
public class OutputNode : OutputItem
{
/// <summary>
/// Node length (number of bytes). This doesn't include any external alignment
/// applied when concatenating the nodes to form sections.
/// </summary>
public readonly int Length;
/// <summary>
/// Number of file-level relocations (.reloc section entries) used by the node.
/// </summary>
public int Relocations { get; private set; }
public OutputNode(int sectionIndex, int offset, int length, string name)
: base(sectionIndex, offset, name)
{
Length = length;
Relocations = 0;
}
public void AddRelocation()
{
Relocations++;
}
}
/// <summary>
/// Symbol is a "pointer" into the PE file. Most (but not all) symbols correspond to
/// node beginnings (most nodes have a "start symbol" representing the beginning
/// of the node).
/// </summary>
public class OutputSymbol : OutputItem
{
public OutputSymbol(int sectionIndex, int offset, string name)
: base(sectionIndex, offset, name)
{
}
}
/// <summary>
/// Common class used to collect information to use when emitting map files and symbol files.
/// </summary>
public class OutputInfoBuilder
{
private readonly List<EcmaModule> _inputModules;
private readonly List<OutputNode> _nodes;
private readonly List<OutputSymbol> _symbols;
private readonly List<Section> _sections;
private readonly Dictionary<ISymbolDefinitionNode, OutputNode> _nodeSymbolMap;
private readonly Dictionary<ISymbolDefinitionNode, MethodWithGCInfo> _methodSymbolMap;
private readonly Dictionary<RelocType, int> _relocCounts;
public OutputInfoBuilder()
{
_inputModules = new List<EcmaModule>();
_nodes = new List<OutputNode>();
_symbols = new List<OutputSymbol>();
_sections = new List<Section>();
_nodeSymbolMap = new Dictionary<ISymbolDefinitionNode, OutputNode>();
_methodSymbolMap = new Dictionary<ISymbolDefinitionNode, MethodWithGCInfo>();
_relocCounts = new Dictionary<RelocType, int>();
}
public void AddInputModule(EcmaModule module)
{
_inputModules.Add(module);
}
public void AddNode(OutputNode node, ISymbolDefinitionNode symbol)
{
_nodes.Add(node);
_nodeSymbolMap.Add(symbol, node);
}
public void AddRelocation(OutputNode node, RelocType relocType)
{
node.AddRelocation();
_relocCounts.TryGetValue(relocType, out int relocTypeCount);
_relocCounts[relocType] = relocTypeCount + 1;
}
public void AddSymbol(OutputSymbol symbol)
{
_symbols.Add(symbol);
}
public void AddSection(Section section)
{
_sections.Add(section);
}
public void AddMethod(MethodWithGCInfo method, ISymbolDefinitionNode symbol)
{
_methodSymbolMap.Add(symbol, method);
}
public void Sort()
{
_nodes.Sort(OutputItem.Comparer.Instance);
_symbols.Sort(OutputItem.Comparer.Instance);
}
public bool FindSymbol(OutputItem item, out int index)
{
index = _symbols.BinarySearch(new OutputSymbol(item.SectionIndex, item.Offset, name: null), OutputItem.Comparer.Instance);
bool result = (index >= 0 && index < _symbols.Count && OutputItem.Comparer.Instance.Compare(_symbols[index], item) == 0);
if (!result)
{
index = -1;
}
return result;
}
public IEnumerable<MethodInfo> EnumerateMethods()
{
DebugNameFormatter nameFormatter = new DebugNameFormatter();
TypeNameFormatter typeNameFormatter = new TypeString();
HashSet<MethodDesc> emittedMethods = new HashSet<MethodDesc>();
foreach (KeyValuePair<ISymbolDefinitionNode, MethodWithGCInfo> symbolMethodPair in _methodSymbolMap)
{
EcmaMethod ecmaMethod = symbolMethodPair.Value.Method.GetTypicalMethodDefinition() as EcmaMethod;
if (ecmaMethod != null && emittedMethods.Add(ecmaMethod))
{
MethodInfo methodInfo = new MethodInfo();
methodInfo.MethodToken = (uint)MetadataTokens.GetToken(ecmaMethod.Handle);
methodInfo.AssemblyName = ecmaMethod.Module.Assembly.GetName().Name;
methodInfo.Name = FormatMethodName(symbolMethodPair.Value.Method, typeNameFormatter);
OutputNode node = _nodeSymbolMap[symbolMethodPair.Key];
Section section = _sections[node.SectionIndex];
methodInfo.HotRVA = (uint)(section.RVAWhenPlaced + node.Offset);
methodInfo.HotLength = (uint)node.Length;
methodInfo.ColdRVA = 0;
methodInfo.ColdLength = 0;
yield return methodInfo;
}
}
}
public IEnumerable<AssemblyInfo> EnumerateInputAssemblies()
{
foreach (EcmaModule inputModule in _inputModules)
{
yield return new AssemblyInfo(
inputModule.Assembly.GetName().Name,
inputModule.MetadataReader.GetGuid(inputModule.MetadataReader.GetModuleDefinition().Mvid));
}
}
private string FormatMethodName(MethodDesc method, TypeNameFormatter typeNameFormatter)
{
StringBuilder output = new StringBuilder();
if (!method.Signature.ReturnType.IsVoid)
{
output.Append(typeNameFormatter.FormatName(method.Signature.ReturnType));
output.Append(" ");
}
output.Append(typeNameFormatter.FormatName(method.OwningType));
output.Append("::");
output.Append(method.Name);
output.Append("(");
for (int paramIndex = 0; paramIndex < method.Signature.Length; paramIndex++)
{
if (paramIndex != 0)
{
output.Append(", ");
}
output.Append(typeNameFormatter.FormatName(method.Signature[paramIndex]));
}
output.Append(")");
return output.ToString();
}
public IReadOnlyList<OutputNode> Nodes => _nodes;
public IReadOnlyList<Section> Sections => _sections;
public IReadOnlyList<OutputSymbol> Symbols => _symbols;
public IReadOnlyDictionary<ISymbolDefinitionNode, OutputNode> NodeSymbolMap => _nodeSymbolMap;
public IReadOnlyDictionary<ISymbolDefinitionNode, MethodWithGCInfo> MethodSymbolMap => _methodSymbolMap;
public IReadOnlyDictionary<RelocType, int> RelocCounts => _relocCounts;
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/Directed/PREFIX/volatile/1/fielda_tests.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="fielda_tests.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="fielda_tests.il" />
</ItemGroup>
</Project>
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/Generics/Fields/instance_passing_class01.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 ValX0 { }
public struct ValY0 { }
public struct ValX1<T> { }
public struct ValY1<T> { }
public struct ValX2<T, U> { }
public struct ValY2<T, U> { }
public struct ValX3<T, U, V> { }
public struct ValY3<T, U, V> { }
public class RefX0 { }
public class RefY0 { }
public class RefX1<T> { }
public class RefY1<T> { }
public class RefX2<T, U> { }
public class RefY2<T, U> { }
public class RefX3<T, U, V> { }
public class RefY3<T, U, V> { }
public class Gen<T>
{
public T Fld1;
public T Fld2;
public T PassAsIn(T t)
{
return t;
}
public T PassAsRef(ref T t)
{
T temp = t;
t = Fld2;
return temp;
}
public void PassAsOut(out T t)
{
t = Fld2;
}
public void PassAsParameter(T t1, T t2)
{
Fld1 = t1;
Fld2 = t2;
T temp = t1;
Test_instance_passing_class01.Eval(Fld1.Equals(PassAsIn(temp)));
Test_instance_passing_class01.Eval(Fld1.Equals(PassAsRef(ref temp)));
Test_instance_passing_class01.Eval(Fld2.Equals(temp));
temp = t1;
PassAsOut(out temp);
Test_instance_passing_class01.Eval(Fld2.Equals(temp));
}
}
public class Test_instance_passing_class01
{
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 _int1 = 1;
int _int2 = -1;
new Gen<int>().PassAsParameter(_int1, _int2);
double _double1 = 1;
double _double2 = -1;
new Gen<double>().PassAsParameter(_double1, _double2);
string _string1 = "string1";
string _string2 = "string2";
new Gen<string>().PassAsParameter(_string1, _string2);
object _object1 = (object)_string1;
object _object2 = (object)_string2;
new Gen<object>().PassAsParameter(_object1, _object2);
Guid _Guid1 = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Guid _Guid2 = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
new Gen<Guid>().PassAsParameter(_Guid1, _Guid2);
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 ValX0 { }
public struct ValY0 { }
public struct ValX1<T> { }
public struct ValY1<T> { }
public struct ValX2<T, U> { }
public struct ValY2<T, U> { }
public struct ValX3<T, U, V> { }
public struct ValY3<T, U, V> { }
public class RefX0 { }
public class RefY0 { }
public class RefX1<T> { }
public class RefY1<T> { }
public class RefX2<T, U> { }
public class RefY2<T, U> { }
public class RefX3<T, U, V> { }
public class RefY3<T, U, V> { }
public class Gen<T>
{
public T Fld1;
public T Fld2;
public T PassAsIn(T t)
{
return t;
}
public T PassAsRef(ref T t)
{
T temp = t;
t = Fld2;
return temp;
}
public void PassAsOut(out T t)
{
t = Fld2;
}
public void PassAsParameter(T t1, T t2)
{
Fld1 = t1;
Fld2 = t2;
T temp = t1;
Test_instance_passing_class01.Eval(Fld1.Equals(PassAsIn(temp)));
Test_instance_passing_class01.Eval(Fld1.Equals(PassAsRef(ref temp)));
Test_instance_passing_class01.Eval(Fld2.Equals(temp));
temp = t1;
PassAsOut(out temp);
Test_instance_passing_class01.Eval(Fld2.Equals(temp));
}
}
public class Test_instance_passing_class01
{
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 _int1 = 1;
int _int2 = -1;
new Gen<int>().PassAsParameter(_int1, _int2);
double _double1 = 1;
double _double2 = -1;
new Gen<double>().PassAsParameter(_double1, _double2);
string _string1 = "string1";
string _string2 = "string2";
new Gen<string>().PassAsParameter(_string1, _string2);
object _object1 = (object)_string1;
object _object2 = (object)_string2;
new Gen<object>().PassAsParameter(_object1, _object2);
Guid _Guid1 = new Guid(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Guid _Guid2 = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
new Gen<Guid>().PassAsParameter(_Guid1, _Guid2);
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.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.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Exposes all the metadata for a specific event Provider. An instance
/// of this class is obtained from EventLogManagement and is scoped to a
/// single Locale.
/// </summary>
public class ProviderMetadata : IDisposable
{
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private readonly EventLogHandle _handle = EventLogHandle.Zero;
private EventLogHandle _defaultProviderHandle = EventLogHandle.Zero;
private readonly EventLogSession _session;
private readonly string _providerName;
private readonly CultureInfo _cultureInfo;
private readonly string _logFilePath;
// caching of the IEnumerable<EventLevel>, <EventTask>, <EventKeyword>, <EventOpcode> on the ProviderMetadata
// they do not change with every call.
private IList<EventLevel> _levels;
private IList<EventOpcode> _opcodes;
private IList<EventTask> _tasks;
private IList<EventKeyword> _keywords;
private IList<EventLevel> _standardLevels;
private IList<EventOpcode> _standardOpcodes;
private IList<EventTask> _standardTasks;
private IList<EventKeyword> _standardKeywords;
private IList<EventLogLink> _channelReferences;
private readonly object _syncObject;
public ProviderMetadata(string providerName)
: this(providerName, null, null, null)
{
}
public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo)
: this(providerName, session, targetCultureInfo, null)
{
}
internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath)
{
if (targetCultureInfo == null)
targetCultureInfo = CultureInfo.CurrentCulture;
if (session == null)
session = EventLogSession.GlobalSession;
_session = session;
_providerName = providerName;
_cultureInfo = targetCultureInfo;
_logFilePath = logFilePath;
_handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0);
_syncObject = new object();
}
internal EventLogHandle Handle
{
get
{
return _handle;
}
}
public string Name
{
get { return _providerName; }
}
public Guid Id
{
get
{
return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid);
}
}
public string MessageFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath);
}
}
public string ResourceFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath);
}
}
public string ParameterFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath);
}
}
public Uri HelpLink
{
get
{
string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink);
if (helpLinkStr == null || helpLinkStr.Length == 0)
return null;
return new Uri(helpLinkStr);
}
}
private uint ProviderMessageID
{
get
{
return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID);
}
}
public string DisplayName
{
get
{
uint msgId = (uint)this.ProviderMessageID;
if (msgId == 0xffffffff)
return null;
return NativeWrapper.EvtFormatMessage(_handle, msgId);
}
}
public IList<EventLogLink> LogLinks
{
get
{
EventLogHandle elHandle = EventLogHandle.Zero;
try
{
lock (_syncObject)
{
if (_channelReferences != null)
return _channelReferences;
elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferences);
int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle);
List<EventLogLink> channelList = new List<EventLogLink>(arraySize);
for (int index = 0; index < arraySize; index++)
{
string channelName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath);
uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID);
uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags);
bool isImported;
if (flag == (int)UnsafeNativeMethods.EvtChannelReferenceFlags.EvtChannelReferenceImported)
isImported = true;
else
isImported = false;
int channelRefMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceMessageID)));
string channelRefDisplayName;
// if channelRefMessageId == -1, we do not have anything in the message table.
if (channelRefMessageId == -1)
{
channelRefDisplayName = null;
}
else
{
channelRefDisplayName = NativeWrapper.EvtFormatMessage(_handle, unchecked((uint)channelRefMessageId));
}
if (channelRefDisplayName == null && isImported)
{
if (string.Equals(channelName, "Application", StringComparison.OrdinalIgnoreCase))
channelRefMessageId = 256;
else if (string.Equals(channelName, "System", StringComparison.OrdinalIgnoreCase))
channelRefMessageId = 258;
else if (string.Equals(channelName, "Security", StringComparison.OrdinalIgnoreCase))
channelRefMessageId = 257;
else
channelRefMessageId = -1;
if (channelRefMessageId != -1)
{
if (_defaultProviderHandle.IsInvalid)
{
_defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0);
}
channelRefDisplayName = NativeWrapper.EvtFormatMessage(_defaultProviderHandle, unchecked((uint)channelRefMessageId));
}
}
channelList.Add(new EventLogLink(channelName, isImported, channelRefDisplayName, channelId));
}
_channelReferences = channelList.AsReadOnly();
}
return _channelReferences;
}
finally
{
elHandle.Dispose();
}
}
}
internal enum ObjectTypeName
{
Level = 0,
Opcode = 1,
Task = 2,
Keyword = 3
}
internal string FindStandardLevelDisplayName(string name, uint value)
{
if (_standardLevels == null)
_standardLevels = (List<EventLevel>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
foreach (EventLevel standardLevel in _standardLevels)
{
if (standardLevel.Name == name && standardLevel.Value == value)
return standardLevel.DisplayName;
}
return null;
}
internal string FindStandardOpcodeDisplayName(string name, uint value)
{
if (_standardOpcodes == null)
_standardOpcodes = (List<EventOpcode>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
foreach (EventOpcode standardOpcode in _standardOpcodes)
{
if (standardOpcode.Name == name && standardOpcode.Value == value)
return standardOpcode.DisplayName;
}
return null;
}
internal string FindStandardKeywordDisplayName(string name, long value)
{
if (_standardKeywords == null)
_standardKeywords = (List<EventKeyword>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
foreach (EventKeyword standardKeyword in _standardKeywords)
{
if (standardKeyword.Name == name && standardKeyword.Value == value)
return standardKeyword.DisplayName;
}
return null;
}
internal string FindStandardTaskDisplayName(string name, uint value)
{
if (_standardTasks == null)
_standardTasks = (List<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
foreach (EventTask standardTask in _standardTasks)
{
if (standardTask.Name == name && standardTask.Value == value)
return standardTask.DisplayName;
}
return null;
}
internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty)
{
EventLogHandle elHandle = EventLogHandle.Zero;
try
{
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propName;
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propValue;
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propMessageId;
ObjectTypeName objectTypeName;
List<EventLevel> levelList = null;
List<EventOpcode> opcodeList = null;
List<EventKeyword> keywordList = null;
List<EventTask> taskList = null;
elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(providerHandle, metadataProperty);
int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle);
switch (metadataProperty)
{
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelMessageID;
objectTypeName = ObjectTypeName.Level;
levelList = new List<EventLevel>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeMessageID;
objectTypeName = ObjectTypeName.Opcode;
opcodeList = new List<EventOpcode>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordMessageID;
objectTypeName = ObjectTypeName.Keyword;
keywordList = new List<EventKeyword>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskMessageID;
objectTypeName = ObjectTypeName.Task;
taskList = new List<EventTask>(arraySize);
break;
default:
return null;
}
for (int index = 0; index < arraySize; index++)
{
string generalName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propName);
uint generalValue = 0;
long generalValueKeyword = 0;
if (objectTypeName != ObjectTypeName.Keyword)
{
generalValue = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue);
}
else
{
generalValueKeyword = unchecked((long)((ulong)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue)));
}
int generalMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propMessageId)));
string generalDisplayName = null;
if (generalMessageId == -1)
{
if (providerHandle != _defaultProviderHandle)
{
if (_defaultProviderHandle.IsInvalid)
{
_defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0);
}
generalDisplayName = objectTypeName switch
{
ObjectTypeName.Level => FindStandardLevelDisplayName(generalName, generalValue),
ObjectTypeName.Opcode => FindStandardOpcodeDisplayName(generalName, generalValue >> 16),
ObjectTypeName.Keyword => FindStandardKeywordDisplayName(generalName, generalValueKeyword),
ObjectTypeName.Task => FindStandardTaskDisplayName(generalName, generalValue),
_ => null,
};
}
}
else
{
generalDisplayName = NativeWrapper.EvtFormatMessage(providerHandle, unchecked((uint)generalMessageId));
}
switch (objectTypeName)
{
case ObjectTypeName.Level:
levelList.Add(new EventLevel(generalName, (int)generalValue, generalDisplayName));
break;
case ObjectTypeName.Opcode:
opcodeList.Add(new EventOpcode(generalName, (int)(generalValue >> 16), generalDisplayName));
break;
case ObjectTypeName.Keyword:
keywordList.Add(new EventKeyword(generalName, (long)generalValueKeyword, generalDisplayName));
break;
case ObjectTypeName.Task:
Guid taskGuid = (Guid)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskEventGuid);
taskList.Add(new EventTask(generalName, (int)generalValue, generalDisplayName, taskGuid));
break;
default:
return null;
}
}
return objectTypeName switch
{
ObjectTypeName.Level => levelList,
ObjectTypeName.Opcode => opcodeList,
ObjectTypeName.Keyword => keywordList,
ObjectTypeName.Task => taskList,
_ => null,
};
}
finally
{
elHandle.Dispose();
}
}
public IList<EventLevel> Levels
{
get
{
List<EventLevel> el;
lock (_syncObject)
{
if (_levels != null)
return _levels;
el = (List<EventLevel>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
_levels = el.AsReadOnly();
}
return _levels;
}
}
public IList<EventOpcode> Opcodes
{
get
{
List<EventOpcode> eo;
lock (_syncObject)
{
if (_opcodes != null)
return _opcodes;
eo = (List<EventOpcode>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
_opcodes = eo.AsReadOnly();
}
return _opcodes;
}
}
public IList<EventKeyword> Keywords
{
get
{
List<EventKeyword> ek;
lock (_syncObject)
{
if (_keywords != null)
return _keywords;
ek = (List<EventKeyword>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
_keywords = ek.AsReadOnly();
}
return _keywords;
}
}
public IList<EventTask> Tasks
{
get
{
List<EventTask> et;
lock (_syncObject)
{
if (_tasks != null)
return _tasks;
et = (List<EventTask>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
_tasks = et.AsReadOnly();
}
return _tasks;
}
}
public IEnumerable<EventMetadata> Events
{
get
{
List<EventMetadata> emList = new List<EventMetadata>();
EventLogHandle emEnumHandle = NativeWrapper.EvtOpenEventMetadataEnum(_handle, 0);
using (emEnumHandle)
{
while (true)
{
EventLogHandle emHandle = emHandle = NativeWrapper.EvtNextEventMetadata(emEnumHandle, 0);
if (emHandle == null)
break;
using (emHandle)
{
unchecked
{
uint emId = (uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventID);
byte emVersion = (byte)((uint)(NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventVersion)));
byte emChannelId = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventChannel));
byte emLevel = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventLevel));
byte emOpcode = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventOpcode));
short emTask = (short)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTask));
long emKeywords = (long)(ulong)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventKeyword);
string emTemplate = (string)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTemplate);
int messageId = (int)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventMessageID));
string emMessage = (messageId == -1)
? null
: NativeWrapper.EvtFormatMessage(_handle, (uint)messageId);
EventMetadata em = new EventMetadata(emId, emVersion, emChannelId, emLevel, emOpcode, emTask, emKeywords, emTemplate, emMessage, this);
emList.Add(em);
}
}
}
return emList.AsReadOnly();
}
}
}
// throws if Provider metadata has been uninstalled since this object was created.
internal void CheckReleased()
{
lock (_syncObject)
{
this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// Exposes all the metadata for a specific event Provider. An instance
/// of this class is obtained from EventLogManagement and is scoped to a
/// single Locale.
/// </summary>
public class ProviderMetadata : IDisposable
{
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private readonly EventLogHandle _handle = EventLogHandle.Zero;
private EventLogHandle _defaultProviderHandle = EventLogHandle.Zero;
private readonly EventLogSession _session;
private readonly string _providerName;
private readonly CultureInfo _cultureInfo;
private readonly string _logFilePath;
// caching of the IEnumerable<EventLevel>, <EventTask>, <EventKeyword>, <EventOpcode> on the ProviderMetadata
// they do not change with every call.
private IList<EventLevel> _levels;
private IList<EventOpcode> _opcodes;
private IList<EventTask> _tasks;
private IList<EventKeyword> _keywords;
private IList<EventLevel> _standardLevels;
private IList<EventOpcode> _standardOpcodes;
private IList<EventTask> _standardTasks;
private IList<EventKeyword> _standardKeywords;
private IList<EventLogLink> _channelReferences;
private readonly object _syncObject;
public ProviderMetadata(string providerName)
: this(providerName, null, null, null)
{
}
public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo)
: this(providerName, session, targetCultureInfo, null)
{
}
internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath)
{
if (targetCultureInfo == null)
targetCultureInfo = CultureInfo.CurrentCulture;
if (session == null)
session = EventLogSession.GlobalSession;
_session = session;
_providerName = providerName;
_cultureInfo = targetCultureInfo;
_logFilePath = logFilePath;
_handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0);
_syncObject = new object();
}
internal EventLogHandle Handle
{
get
{
return _handle;
}
}
public string Name
{
get { return _providerName; }
}
public Guid Id
{
get
{
return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid);
}
}
public string MessageFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath);
}
}
public string ResourceFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath);
}
}
public string ParameterFilePath
{
get
{
return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath);
}
}
public Uri HelpLink
{
get
{
string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink);
if (helpLinkStr == null || helpLinkStr.Length == 0)
return null;
return new Uri(helpLinkStr);
}
}
private uint ProviderMessageID
{
get
{
return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID);
}
}
public string DisplayName
{
get
{
uint msgId = (uint)this.ProviderMessageID;
if (msgId == 0xffffffff)
return null;
return NativeWrapper.EvtFormatMessage(_handle, msgId);
}
}
public IList<EventLogLink> LogLinks
{
get
{
EventLogHandle elHandle = EventLogHandle.Zero;
try
{
lock (_syncObject)
{
if (_channelReferences != null)
return _channelReferences;
elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferences);
int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle);
List<EventLogLink> channelList = new List<EventLogLink>(arraySize);
for (int index = 0; index < arraySize; index++)
{
string channelName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath);
uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID);
uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags);
bool isImported;
if (flag == (int)UnsafeNativeMethods.EvtChannelReferenceFlags.EvtChannelReferenceImported)
isImported = true;
else
isImported = false;
int channelRefMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceMessageID)));
string channelRefDisplayName;
// if channelRefMessageId == -1, we do not have anything in the message table.
if (channelRefMessageId == -1)
{
channelRefDisplayName = null;
}
else
{
channelRefDisplayName = NativeWrapper.EvtFormatMessage(_handle, unchecked((uint)channelRefMessageId));
}
if (channelRefDisplayName == null && isImported)
{
if (string.Equals(channelName, "Application", StringComparison.OrdinalIgnoreCase))
channelRefMessageId = 256;
else if (string.Equals(channelName, "System", StringComparison.OrdinalIgnoreCase))
channelRefMessageId = 258;
else if (string.Equals(channelName, "Security", StringComparison.OrdinalIgnoreCase))
channelRefMessageId = 257;
else
channelRefMessageId = -1;
if (channelRefMessageId != -1)
{
if (_defaultProviderHandle.IsInvalid)
{
_defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0);
}
channelRefDisplayName = NativeWrapper.EvtFormatMessage(_defaultProviderHandle, unchecked((uint)channelRefMessageId));
}
}
channelList.Add(new EventLogLink(channelName, isImported, channelRefDisplayName, channelId));
}
_channelReferences = channelList.AsReadOnly();
}
return _channelReferences;
}
finally
{
elHandle.Dispose();
}
}
}
internal enum ObjectTypeName
{
Level = 0,
Opcode = 1,
Task = 2,
Keyword = 3
}
internal string FindStandardLevelDisplayName(string name, uint value)
{
if (_standardLevels == null)
_standardLevels = (List<EventLevel>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
foreach (EventLevel standardLevel in _standardLevels)
{
if (standardLevel.Name == name && standardLevel.Value == value)
return standardLevel.DisplayName;
}
return null;
}
internal string FindStandardOpcodeDisplayName(string name, uint value)
{
if (_standardOpcodes == null)
_standardOpcodes = (List<EventOpcode>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
foreach (EventOpcode standardOpcode in _standardOpcodes)
{
if (standardOpcode.Name == name && standardOpcode.Value == value)
return standardOpcode.DisplayName;
}
return null;
}
internal string FindStandardKeywordDisplayName(string name, long value)
{
if (_standardKeywords == null)
_standardKeywords = (List<EventKeyword>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
foreach (EventKeyword standardKeyword in _standardKeywords)
{
if (standardKeyword.Name == name && standardKeyword.Value == value)
return standardKeyword.DisplayName;
}
return null;
}
internal string FindStandardTaskDisplayName(string name, uint value)
{
if (_standardTasks == null)
_standardTasks = (List<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
foreach (EventTask standardTask in _standardTasks)
{
if (standardTask.Name == name && standardTask.Value == value)
return standardTask.DisplayName;
}
return null;
}
internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty)
{
EventLogHandle elHandle = EventLogHandle.Zero;
try
{
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propName;
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propValue;
UnsafeNativeMethods.EvtPublisherMetadataPropertyId propMessageId;
ObjectTypeName objectTypeName;
List<EventLevel> levelList = null;
List<EventOpcode> opcodeList = null;
List<EventKeyword> keywordList = null;
List<EventTask> taskList = null;
elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(providerHandle, metadataProperty);
int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle);
switch (metadataProperty)
{
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelMessageID;
objectTypeName = ObjectTypeName.Level;
levelList = new List<EventLevel>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeMessageID;
objectTypeName = ObjectTypeName.Opcode;
opcodeList = new List<EventOpcode>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordMessageID;
objectTypeName = ObjectTypeName.Keyword;
keywordList = new List<EventKeyword>(arraySize);
break;
case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks:
propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskName;
propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskValue;
propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskMessageID;
objectTypeName = ObjectTypeName.Task;
taskList = new List<EventTask>(arraySize);
break;
default:
return null;
}
for (int index = 0; index < arraySize; index++)
{
string generalName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propName);
uint generalValue = 0;
long generalValueKeyword = 0;
if (objectTypeName != ObjectTypeName.Keyword)
{
generalValue = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue);
}
else
{
generalValueKeyword = unchecked((long)((ulong)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue)));
}
int generalMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propMessageId)));
string generalDisplayName = null;
if (generalMessageId == -1)
{
if (providerHandle != _defaultProviderHandle)
{
if (_defaultProviderHandle.IsInvalid)
{
_defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0);
}
generalDisplayName = objectTypeName switch
{
ObjectTypeName.Level => FindStandardLevelDisplayName(generalName, generalValue),
ObjectTypeName.Opcode => FindStandardOpcodeDisplayName(generalName, generalValue >> 16),
ObjectTypeName.Keyword => FindStandardKeywordDisplayName(generalName, generalValueKeyword),
ObjectTypeName.Task => FindStandardTaskDisplayName(generalName, generalValue),
_ => null,
};
}
}
else
{
generalDisplayName = NativeWrapper.EvtFormatMessage(providerHandle, unchecked((uint)generalMessageId));
}
switch (objectTypeName)
{
case ObjectTypeName.Level:
levelList.Add(new EventLevel(generalName, (int)generalValue, generalDisplayName));
break;
case ObjectTypeName.Opcode:
opcodeList.Add(new EventOpcode(generalName, (int)(generalValue >> 16), generalDisplayName));
break;
case ObjectTypeName.Keyword:
keywordList.Add(new EventKeyword(generalName, (long)generalValueKeyword, generalDisplayName));
break;
case ObjectTypeName.Task:
Guid taskGuid = (Guid)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskEventGuid);
taskList.Add(new EventTask(generalName, (int)generalValue, generalDisplayName, taskGuid));
break;
default:
return null;
}
}
return objectTypeName switch
{
ObjectTypeName.Level => levelList,
ObjectTypeName.Opcode => opcodeList,
ObjectTypeName.Keyword => keywordList,
ObjectTypeName.Task => taskList,
_ => null,
};
}
finally
{
elHandle.Dispose();
}
}
public IList<EventLevel> Levels
{
get
{
List<EventLevel> el;
lock (_syncObject)
{
if (_levels != null)
return _levels;
el = (List<EventLevel>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels);
_levels = el.AsReadOnly();
}
return _levels;
}
}
public IList<EventOpcode> Opcodes
{
get
{
List<EventOpcode> eo;
lock (_syncObject)
{
if (_opcodes != null)
return _opcodes;
eo = (List<EventOpcode>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes);
_opcodes = eo.AsReadOnly();
}
return _opcodes;
}
}
public IList<EventKeyword> Keywords
{
get
{
List<EventKeyword> ek;
lock (_syncObject)
{
if (_keywords != null)
return _keywords;
ek = (List<EventKeyword>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords);
_keywords = ek.AsReadOnly();
}
return _keywords;
}
}
public IList<EventTask> Tasks
{
get
{
List<EventTask> et;
lock (_syncObject)
{
if (_tasks != null)
return _tasks;
et = (List<EventTask>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
_tasks = et.AsReadOnly();
}
return _tasks;
}
}
public IEnumerable<EventMetadata> Events
{
get
{
List<EventMetadata> emList = new List<EventMetadata>();
EventLogHandle emEnumHandle = NativeWrapper.EvtOpenEventMetadataEnum(_handle, 0);
using (emEnumHandle)
{
while (true)
{
EventLogHandle emHandle = emHandle = NativeWrapper.EvtNextEventMetadata(emEnumHandle, 0);
if (emHandle == null)
break;
using (emHandle)
{
unchecked
{
uint emId = (uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventID);
byte emVersion = (byte)((uint)(NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventVersion)));
byte emChannelId = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventChannel));
byte emLevel = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventLevel));
byte emOpcode = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventOpcode));
short emTask = (short)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTask));
long emKeywords = (long)(ulong)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventKeyword);
string emTemplate = (string)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTemplate);
int messageId = (int)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventMessageID));
string emMessage = (messageId == -1)
? null
: NativeWrapper.EvtFormatMessage(_handle, (uint)messageId);
EventMetadata em = new EventMetadata(emId, emVersion, emChannelId, emLevel, emOpcode, emTask, emKeywords, emTemplate, emMessage, this);
emList.Add(em);
}
}
}
return emList.AsReadOnly();
}
}
}
// throws if Provider metadata has been uninstalled since this object was created.
internal void CheckReleased()
{
lock (_syncObject)
{
this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/oft1.txt | <?xml version="1.0" encoding="utf-8"?>Hello, world! | <?xml version="1.0" encoding="utf-8"?>Hello, world! | -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int64Converter.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;
namespace System.ComponentModel
{
/// <summary>
/// Provides a type converter to convert 64-bit signed integer objects to and
/// from various other representations.
/// </summary>
public class Int64Converter : BaseNumberConverter
{
/// <summary>
/// The Type this converter is targeting (e.g. Int16, UInt32, etc.)
/// </summary>
internal override Type TargetType => typeof(long);
/// <summary>
/// Convert the given value to a string using the given radix
/// </summary>
internal override object FromString(string value, int radix) => Convert.ToInt64(value, radix);
/// <summary>
/// Convert the given value to a string using the given formatInfo
/// </summary>
internal override object FromString(string value, NumberFormatInfo? formatInfo)
{
return long.Parse(value, NumberStyles.Integer, formatInfo);
}
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
internal override string ToString(object value, NumberFormatInfo? formatInfo)
{
return ((long)value).ToString("G", formatInfo);
}
}
}
| // 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;
namespace System.ComponentModel
{
/// <summary>
/// Provides a type converter to convert 64-bit signed integer objects to and
/// from various other representations.
/// </summary>
public class Int64Converter : BaseNumberConverter
{
/// <summary>
/// The Type this converter is targeting (e.g. Int16, UInt32, etc.)
/// </summary>
internal override Type TargetType => typeof(long);
/// <summary>
/// Convert the given value to a string using the given radix
/// </summary>
internal override object FromString(string value, int radix) => Convert.ToInt64(value, radix);
/// <summary>
/// Convert the given value to a string using the given formatInfo
/// </summary>
internal override object FromString(string value, NumberFormatInfo? formatInfo)
{
return long.Parse(value, NumberStyles.Integer, formatInfo);
}
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
internal override string ToString(object value, NumberFormatInfo? formatInfo)
{
return ((long)value).ToString("G", formatInfo);
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/Common/tests/System/Xml/ModuleCore/cltmconsole.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.Text;
using System.Diagnostics;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// CLTMConsole
//
////////////////////////////////////////////////////////////////
public class CLTMConsole : TextWriter
{
//Data
//Constructor
public CLTMConsole()
{
}
//Overloads - A subclass must minimally implement the Write(Char) method.
public override void Write(char ch)
{
CError.Write(ch.ToString());
}
//Overloads - We also implement "string" since its much more efficient and TextWriter will call this instead
public override void Write(string strText)
{
CError.Write(strText);
}
//Overloads - We also implement "string" since its much more efficient and TextWriter will call this instead
public override void Write(char[] ch)
{
//Note: This is a workaround the TextWriter::Write(char[]) that incorrectly
//writes 1 char at a time, which means \r\n is written separately and then gets fixed
//up to be two carriage returns!
if (ch != null)
{
Write(new string(ch));
}
}
public override void WriteLine(string strText)
{
Write(strText + this.NewLine);
}
//Overloads
//Writes a line terminator to the text stream.
//The default line terminator is a carriage return followed by a line feed ("\r\n"),
//but this value can be changed using the NewLine property.
public override void WriteLine()
{
Write(this.NewLine);
}
//Overloads
public override Encoding Encoding
{
get { return Encoding.Unicode; }
}
}
////////////////////////////////////////////////////////////////
// CLTMTraceListener
//
////////////////////////////////////////////////////////////////
public class CLTMTraceListener //: TraceListener
{
//Data
//Constructor
public CLTMTraceListener()
{
}
}
}
| // 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.Text;
using System.Diagnostics;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// CLTMConsole
//
////////////////////////////////////////////////////////////////
public class CLTMConsole : TextWriter
{
//Data
//Constructor
public CLTMConsole()
{
}
//Overloads - A subclass must minimally implement the Write(Char) method.
public override void Write(char ch)
{
CError.Write(ch.ToString());
}
//Overloads - We also implement "string" since its much more efficient and TextWriter will call this instead
public override void Write(string strText)
{
CError.Write(strText);
}
//Overloads - We also implement "string" since its much more efficient and TextWriter will call this instead
public override void Write(char[] ch)
{
//Note: This is a workaround the TextWriter::Write(char[]) that incorrectly
//writes 1 char at a time, which means \r\n is written separately and then gets fixed
//up to be two carriage returns!
if (ch != null)
{
Write(new string(ch));
}
}
public override void WriteLine(string strText)
{
Write(strText + this.NewLine);
}
//Overloads
//Writes a line terminator to the text stream.
//The default line terminator is a carriage return followed by a line feed ("\r\n"),
//but this value can be changed using the NewLine property.
public override void WriteLine()
{
Write(this.NewLine);
}
//Overloads
public override Encoding Encoding
{
get { return Encoding.Unicode; }
}
}
////////////////////////////////////////////////////////////////
// CLTMTraceListener
//
////////////////////////////////////////////////////////////////
public class CLTMTraceListener //: TraceListener
{
//Data
//Constructor
public CLTMTraceListener()
{
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/Loader/classloader/generics/GenericMethods/method001h.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="method001h.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="method001h.cs" />
</ItemGroup>
</Project>
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/coreclr/pal/src/libunwind/include/tdep-mips/dwarf-config.h | /* libunwind - a platform-independent unwind library
Copyright (C) 2008 CodeSourcery
Copyright (C) 2012 Tommi Rantala <[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. */
#ifndef dwarf_config_h
#define dwarf_config_h
/* This is FIRST_PSEUDO_REGISTER in GCC, since DWARF_FRAME_REGISTERS is not
explicitly defined. */
#define DWARF_NUM_PRESERVED_REGS 188
#define dwarf_to_unw_regnum(reg) (((reg) < 32) ? (reg) : 0)
/* Return TRUE if the ADDR_SPACE uses big-endian byte-order. */
#define dwarf_is_big_endian(addr_space) ((addr_space)->big_endian)
/* Convert a pointer to a dwarf_cursor structure to a pointer to
unw_cursor_t. */
#define dwarf_to_cursor(c) ((unw_cursor_t *) (c))
typedef struct dwarf_loc
{
unw_word_t val;
#ifndef UNW_LOCAL_ONLY
unw_word_t type; /* see DWARF_LOC_TYPE_* macros. */
#endif
}
dwarf_loc_t;
#endif /* dwarf_config_h */
| /* libunwind - a platform-independent unwind library
Copyright (C) 2008 CodeSourcery
Copyright (C) 2012 Tommi Rantala <[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. */
#ifndef dwarf_config_h
#define dwarf_config_h
/* This is FIRST_PSEUDO_REGISTER in GCC, since DWARF_FRAME_REGISTERS is not
explicitly defined. */
#define DWARF_NUM_PRESERVED_REGS 188
#define dwarf_to_unw_regnum(reg) (((reg) < 32) ? (reg) : 0)
/* Return TRUE if the ADDR_SPACE uses big-endian byte-order. */
#define dwarf_is_big_endian(addr_space) ((addr_space)->big_endian)
/* Convert a pointer to a dwarf_cursor structure to a pointer to
unw_cursor_t. */
#define dwarf_to_cursor(c) ((unw_cursor_t *) (c))
typedef struct dwarf_loc
{
unw_word_t val;
#ifndef UNW_LOCAL_ONLY
unw_word_t type; /* see DWARF_LOC_TYPE_* macros. */
#endif
}
dwarf_loc_t;
#endif /* dwarf_config_h */
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/mono/mono/sgen/sgen-gchandles.c | /**
* \file
* SGen GC handles.
*
* Copyright (C) 2015 Xamarin Inc
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include "config.h"
#ifdef HAVE_SGEN_GC
#include "mono/sgen/sgen-gc.h"
#include "mono/sgen/sgen-client.h"
#include "mono/sgen/sgen-array-list.h"
#include "mono/utils/mono-membar.h"
#ifdef HEAVY_STATISTICS
static volatile guint32 stat_gc_handles_allocated = 0;
static volatile guint32 stat_gc_handles_max_allocated = 0;
#endif
#ifndef DISABLE_SGEN_DEBUG_HELPERS
typedef struct {
size_t num_handles [HANDLE_TYPE_MAX];
} GCHandleClassEntry;
static gboolean do_gchandle_stats = FALSE;
static SgenHashTable gchandle_class_hash_table = SGEN_HASH_TABLE_INIT (INTERNAL_MEM_STATISTICS, INTERNAL_MEM_STAT_GCHANDLE_CLASS, sizeof (GCHandleClassEntry), g_str_hash, g_str_equal);
#endif
/*
* A table of GC handle data, implementing a simple lock-free bitmap allocator.
*
* Each entry in a bucket is a pointer with two tag bits: if
* 'GC_HANDLE_OCCUPIED' returns true for a slot, then the slot is occupied; if
* so, then 'GC_HANDLE_VALID' gives whether the entry refers to a valid (1) or
* NULL (0) object reference. If the reference is valid, then the pointer is an
* object pointer. If the reference is NULL, and 'GC_HANDLE_TYPE_IS_WEAK' is
* true for 'type', then the pointer is a metadata pointer--this allows us to
* retrieve the domain ID of an expired weak reference in Mono.
*/
typedef struct {
SgenArrayList entries_array;
guint8 type;
} HandleData;
static void
protocol_gchandle_update (int handle_type, gpointer link, gpointer old_value, gpointer new_value)
{
gboolean old = MONO_GC_HANDLE_IS_OBJECT_POINTER (old_value);
gboolean new_ = MONO_GC_HANDLE_IS_OBJECT_POINTER (new_value);
gboolean track = handle_type == HANDLE_WEAK_TRACK;
if (!MONO_GC_HANDLE_TYPE_IS_WEAK (handle_type))
return;
if (!old && new_)
sgen_binary_protocol_dislink_add (link, MONO_GC_REVEAL_POINTER (new_value, TRUE), track);
else if (old && !new_)
sgen_binary_protocol_dislink_remove (link, track);
else if (old && new_ && old_value != new_value)
sgen_binary_protocol_dislink_update (link, MONO_GC_REVEAL_POINTER (new_value, TRUE), track);
}
/* Returns the new value in the slot, or NULL if the CAS failed. */
static gpointer
try_set_slot (volatile gpointer *slot, GCObject *obj, gpointer old, GCHandleType type)
{
gpointer new_;
if (obj)
new_ = MONO_GC_HANDLE_OBJECT_POINTER (obj, GC_HANDLE_TYPE_IS_WEAK (type));
else
new_ = MONO_GC_HANDLE_METADATA_POINTER (sgen_client_default_metadata (), GC_HANDLE_TYPE_IS_WEAK (type));
SGEN_ASSERT (0, new_, "Why is the occupied bit not set?");
if (mono_atomic_cas_ptr (slot, new_, old) == old) {
protocol_gchandle_update (type, (gpointer)slot, old, new_);
return new_;
}
return NULL;
}
static gboolean
is_slot_set (volatile gpointer *slot)
{
gpointer entry = *slot;
if (MONO_GC_HANDLE_OCCUPIED (entry))
return TRUE;
return FALSE;
}
/* Try to claim a slot by setting its occupied bit. */
static gboolean
try_occupy_slot (volatile gpointer *slot, gpointer obj, int data)
{
if (is_slot_set (slot))
return FALSE;
return try_set_slot (slot, (GCObject *)obj, NULL, (GCHandleType)data) != NULL;
}
static void
bucket_alloc_callback (gpointer *bucket, guint32 new_bucket_size, gboolean alloc)
{
if (alloc)
sgen_register_root ((char *)bucket, new_bucket_size, SGEN_DESCRIPTOR_NULL, ROOT_TYPE_PINNED, MONO_ROOT_SOURCE_GC_HANDLE, NULL, "GC Handle Bucket (SGen, Pinned)");
else
sgen_deregister_root ((char *)bucket);
}
static void
bucket_alloc_report_root (gpointer *bucket, guint32 new_bucket_size, gboolean alloc)
{
if (alloc)
sgen_client_root_registered ((char *)bucket, new_bucket_size, MONO_ROOT_SOURCE_GC_HANDLE, NULL, "GC Handle Bucket (SGen, Normal)");
else
sgen_client_root_deregistered ((char *)bucket);
}
static HandleData gc_handles [] = {
{ SGEN_ARRAY_LIST_INIT (NULL, is_slot_set, try_occupy_slot, -1), (HANDLE_WEAK) },
{ SGEN_ARRAY_LIST_INIT (NULL, is_slot_set, try_occupy_slot, -1), (HANDLE_WEAK_TRACK) },
{ SGEN_ARRAY_LIST_INIT (bucket_alloc_report_root, is_slot_set, try_occupy_slot, -1), (HANDLE_NORMAL) },
{ SGEN_ARRAY_LIST_INIT (bucket_alloc_callback, is_slot_set, try_occupy_slot, -1), (HANDLE_PINNED) },
{ SGEN_ARRAY_LIST_INIT (NULL, is_slot_set, try_occupy_slot, -1), (HANDLE_WEAK_FIELDS) },
};
static HandleData *
gc_handles_for_type (GCHandleType type)
{
return type < HANDLE_TYPE_MAX ? &gc_handles [type] : NULL;
}
/* This assumes that the world is stopped. */
void
sgen_mark_normal_gc_handles (void *addr, SgenUserMarkFunc mark_func, void *gc_data)
{
HandleData *handles = gc_handles_for_type (HANDLE_NORMAL);
SgenArrayList *array = &handles->entries_array;
volatile gpointer *slot;
gpointer hidden, revealed;
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
revealed = MONO_GC_REVEAL_POINTER (hidden, FALSE);
if (!MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden))
continue;
mark_func ((MonoObject **)&revealed, gc_data);
g_assert (revealed);
*slot = MONO_GC_HANDLE_OBJECT_POINTER (revealed, FALSE);
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
void
sgen_gc_handles_report_roots (SgenUserReportRootFunc report_func, void *gc_data)
{
HandleData *handles = gc_handles_for_type (HANDLE_NORMAL);
SgenArrayList *array = &handles->entries_array;
volatile gpointer *slot;
gpointer hidden, revealed;
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
revealed = MONO_GC_REVEAL_POINTER (hidden, FALSE);
if (MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden))
report_func ((void*)slot, (GCObject*)revealed, gc_data);
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
static guint32
alloc_handle (HandleData *handles, GCObject *obj, gboolean track)
{
guint32 res, index;
SgenArrayList *array = &handles->entries_array;
/*
* If a GC happens shortly after a new bucket is allocated, the entire
* bucket could be scanned even though it's mostly empty. To avoid this,
* we track the maximum index seen so far, so that we can skip the empty
* slots.
*
* Note that we update `next_slot` before we even try occupying the
* slot. If we did it the other way around and a GC happened in
* between, the GC wouldn't know that the slot was occupied. This is
* not a huge deal since `obj` is on the stack and thus pinned anyway,
* but hopefully some day it won't be anymore.
*/
index = sgen_array_list_add (array, obj, handles->type, TRUE);
#ifdef HEAVY_STATISTICS
mono_atomic_inc_i32 ((volatile gint32 *)&stat_gc_handles_allocated);
if (stat_gc_handles_allocated > stat_gc_handles_max_allocated)
stat_gc_handles_max_allocated = stat_gc_handles_allocated;
#endif
/* Ensure that a GC handle cannot be given to another thread without the slot having been set. */
mono_memory_write_barrier ();
res = MONO_GC_HANDLE (index, handles->type);
sgen_client_gchandle_created ((GCHandleType)handles->type, obj, res);
return res;
}
static gboolean
object_older_than (GCObject *object, int generation)
{
return generation == GENERATION_NURSERY && !sgen_ptr_in_nursery (object);
}
/*
* Maps a function over all GC handles.
* This assumes that the world is stopped!
*/
void
sgen_gchandle_iterate (GCHandleType handle_type, int max_generation, SgenGCHandleIterateCallback callback, gpointer user)
{
HandleData *handle_data = gc_handles_for_type (handle_type);
SgenArrayList *array = &handle_data->entries_array;
gpointer hidden, result, occupied;
volatile gpointer *slot;
/* If a new bucket has been allocated, but the capacity has not yet been
* increased, nothing can yet have been allocated in the bucket because the
* world is stopped, so we shouldn't miss any handles during iteration.
*/
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
occupied = (gpointer) MONO_GC_HANDLE_OCCUPIED (hidden);
g_assert (hidden ? !!occupied : !occupied);
if (!occupied)
continue;
result = callback (hidden, handle_type, max_generation, user);
if (result)
SGEN_ASSERT (0, MONO_GC_HANDLE_OCCUPIED (result), "Why did the callback return an unoccupied entry?");
else
HEAVY_STAT (mono_atomic_dec_i32 ((volatile gint32 *)&stat_gc_handles_allocated));
protocol_gchandle_update (handle_type, (gpointer)slot, hidden, result);
*slot = result;
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
guint32
sgen_gchandle_new (GCObject *obj, gboolean pinned)
{
return alloc_handle (gc_handles_for_type (pinned ? HANDLE_PINNED : HANDLE_NORMAL), obj, FALSE);
}
guint32
sgen_gchandle_new_weakref (GCObject *obj, gboolean track_resurrection)
{
return alloc_handle (gc_handles_for_type (track_resurrection ? HANDLE_WEAK_TRACK : HANDLE_WEAK), obj, track_resurrection);
}
static GCObject *
link_get (volatile gpointer *link_addr, gboolean is_weak)
{
void *volatile *link_addr_volatile;
void *ptr;
GCObject *obj;
retry:
link_addr_volatile = link_addr;
ptr = (void*)*link_addr_volatile;
/*
* At this point we have a hidden pointer. If the GC runs
* here, it will not recognize the hidden pointer as a
* reference, and if the object behind it is not referenced
* elsewhere, it will be freed. Once the world is restarted
* we reveal the pointer, giving us a pointer to a freed
* object. To make sure we don't return it, we load the
* hidden pointer again. If it's still the same, we can be
* sure the object reference is valid.
*/
if (ptr && MONO_GC_HANDLE_IS_OBJECT_POINTER (ptr))
obj = (GCObject *)MONO_GC_REVEAL_POINTER (ptr, is_weak);
else
return NULL;
/* Note [dummy use]:
*
* If a GC happens here, obj needs to be on the stack or in a
* register, so we need to prevent this from being reordered
* wrt the check.
*/
sgen_dummy_use (obj);
mono_memory_barrier ();
if (is_weak)
sgen_client_ensure_weak_gchandles_accessible ();
if ((void*)*link_addr_volatile != ptr)
goto retry;
return obj;
}
GCObject*
sgen_gchandle_get_target (guint32 gchandle)
{
guint index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
/* Invalid handles are possible; accessing one should produce NULL. (#34276) */
if (!handles)
return NULL;
return link_get (sgen_array_list_get_slot (&handles->entries_array, index), MONO_GC_HANDLE_TYPE_IS_WEAK (type));
}
void
sgen_gchandle_set_target (guint32 gchandle, GCObject *obj)
{
guint32 index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
volatile gpointer *slot;
gpointer entry;
if (!handles)
return;
slot = sgen_array_list_get_slot (&handles->entries_array, index);
do {
entry = *slot;
SGEN_ASSERT (0, MONO_GC_HANDLE_OCCUPIED (entry), "Why are we setting the target on an unoccupied slot?");
} while (!try_set_slot (slot, obj, entry, (GCHandleType)handles->type));
}
static gpointer
mono_gchandle_slot_metadata (volatile gpointer *slot, gboolean is_weak)
{
gpointer entry;
gpointer metadata;
retry:
entry = *slot;
if (!MONO_GC_HANDLE_OCCUPIED (entry))
return NULL;
if (MONO_GC_HANDLE_IS_OBJECT_POINTER (entry)) {
GCObject *obj = (GCObject *)MONO_GC_REVEAL_POINTER (entry, is_weak);
/* See note [dummy use]. */
sgen_dummy_use (obj);
/*
* FIXME: The compiler could technically not carry a reference to obj around
* at this point and recompute it later, in which case we would still use
* it.
*/
if (*slot != entry)
goto retry;
return sgen_client_metadata_for_object (obj);
}
metadata = MONO_GC_REVEAL_POINTER (entry, is_weak);
/* See note [dummy use]. */
sgen_dummy_use (metadata);
if (*slot != entry)
goto retry;
return metadata;
}
gpointer
sgen_gchandle_get_metadata (guint32 gchandle)
{
guint32 index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
volatile gpointer *slot;
if (!handles)
return NULL;
if (index >= handles->entries_array.capacity)
return NULL;
slot = sgen_array_list_get_slot (&handles->entries_array, index);
return mono_gchandle_slot_metadata (slot, MONO_GC_HANDLE_TYPE_IS_WEAK (type));
}
void
sgen_gchandle_free (guint32 gchandle)
{
if (!gchandle)
return;
guint32 index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
volatile gpointer *slot;
gpointer entry;
if (!handles)
return;
slot = sgen_array_list_get_slot (&handles->entries_array, index);
entry = *slot;
if (index < handles->entries_array.capacity && MONO_GC_HANDLE_OCCUPIED (entry)) {
*slot = NULL;
protocol_gchandle_update (handles->type, (gpointer)slot, entry, NULL);
HEAVY_STAT (mono_atomic_dec_i32 ((volatile gint32 *)&stat_gc_handles_allocated));
} else {
/* print a warning? */
}
sgen_client_gchandle_destroyed ((GCHandleType)handles->type, gchandle);
}
/*
* Returns whether to remove the link from its hash.
*/
static gpointer
null_link_if_necessary (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user)
{
const gboolean is_weak = GC_HANDLE_TYPE_IS_WEAK (handle_type);
ScanCopyContext *ctx = (ScanCopyContext *)user;
GCObject *obj;
GCObject *copy;
if (!MONO_GC_HANDLE_VALID (hidden))
return hidden;
obj = (GCObject *)MONO_GC_REVEAL_POINTER (hidden, MONO_GC_HANDLE_TYPE_IS_WEAK (handle_type));
SGEN_ASSERT (0, obj, "Why is the hidden pointer NULL?");
if (object_older_than (obj, max_generation))
return hidden;
if (sgen_major_collector.is_object_live (obj))
return hidden;
/* Clear link if object is ready for finalization. This check may be redundant wrt is_object_live(). */
if (sgen_gc_is_object_ready_for_finalization (obj))
return MONO_GC_HANDLE_METADATA_POINTER (sgen_client_metadata_for_object (obj), is_weak);
copy = obj;
ctx->ops->copy_or_mark_object (©, ctx->queue);
SGEN_ASSERT (0, copy, "Why couldn't we copy the object?");
/* Update link if object was moved. */
return MONO_GC_HANDLE_OBJECT_POINTER (copy, is_weak);
}
static gpointer
scan_for_weak (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user)
{
const gboolean is_weak = GC_HANDLE_TYPE_IS_WEAK (handle_type);
ScanCopyContext *ctx = (ScanCopyContext *)user;
if (!MONO_GC_HANDLE_VALID (hidden))
return hidden;
GCObject *obj = (GCObject *)MONO_GC_REVEAL_POINTER (hidden, is_weak);
/* If the object is dead we free the gc handle */
if (!sgen_is_object_alive_for_current_gen (obj))
return NULL;
/* Relocate it */
ctx->ops->copy_or_mark_object (&obj, ctx->queue);
int nbits;
gsize *weak_bitmap = sgen_client_get_weak_bitmap (SGEN_LOAD_VTABLE (obj), &nbits);
for (int i = 0; i < nbits; ++i) {
if (weak_bitmap [i / (sizeof (gsize) * 8)] & ((gsize)1 << (i % (sizeof (gsize) * 8)))) {
GCObject **addr = (GCObject **)((char*)obj + (i * sizeof (gpointer)));
GCObject *field = *addr;
/* if the object in the weak field is alive, we relocate it */
if (field && sgen_is_object_alive_for_current_gen (field))
ctx->ops->copy_or_mark_object (addr, ctx->queue);
else
*addr = NULL;
}
}
/* Update link if object was moved. */
return MONO_GC_HANDLE_OBJECT_POINTER (obj, is_weak);
}
/* LOCKING: requires that the GC lock is held */
void
sgen_null_link_in_range (int generation, ScanCopyContext ctx, gboolean track)
{
sgen_gchandle_iterate (track ? HANDLE_WEAK_TRACK : HANDLE_WEAK, generation, null_link_if_necessary, &ctx);
//we're always called for gen zero. !track means short ref
if (generation == 0 && !track)
sgen_gchandle_iterate (HANDLE_WEAK_FIELDS, generation, scan_for_weak, &ctx);
}
typedef struct {
SgenObjectPredicateFunc predicate;
gpointer data;
} WeakLinkAlivePredicateClosure;
static gpointer
null_link_if (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user)
{
WeakLinkAlivePredicateClosure *closure = (WeakLinkAlivePredicateClosure *)user;
GCObject *obj;
if (!MONO_GC_HANDLE_VALID (hidden))
return hidden;
obj = (GCObject *)MONO_GC_REVEAL_POINTER (hidden, MONO_GC_HANDLE_TYPE_IS_WEAK (handle_type));
SGEN_ASSERT (0, obj, "Why is the hidden pointer NULL?");
if (object_older_than (obj, max_generation))
return hidden;
if (closure->predicate (obj, closure->data))
return MONO_GC_HANDLE_METADATA_POINTER (sgen_client_default_metadata (), GC_HANDLE_TYPE_IS_WEAK (handle_type));
return hidden;
}
/* LOCKING: requires that the GC lock is held */
void
sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track)
{
WeakLinkAlivePredicateClosure closure = { predicate, data };
sgen_gchandle_iterate (track ? HANDLE_WEAK_TRACK : HANDLE_WEAK, generation, null_link_if, &closure);
}
void
sgen_register_obj_with_weak_fields (GCObject *obj)
{
//
// We use a gc handle to be able to do some processing for these objects at every gc
//
alloc_handle (gc_handles_for_type (HANDLE_WEAK_FIELDS), obj, FALSE);
}
#ifndef DISABLE_SGEN_DEBUG_HELPERS
void
sgen_gchandle_stats_enable (void)
{
do_gchandle_stats = TRUE;
}
static void
sgen_gchandle_stats_register_vtable (GCVTable vtable, int handle_type)
{
GCHandleClassEntry *entry;
char *name = g_strdup_printf ("%s.%s", sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable));
entry = (GCHandleClassEntry*) sgen_hash_table_lookup (&gchandle_class_hash_table, name);
if (entry) {
g_free (name);
} else {
// Create the entry for this class and get the address of it
GCHandleClassEntry empty_entry;
memset (&empty_entry, 0, sizeof (GCHandleClassEntry));
sgen_hash_table_replace (&gchandle_class_hash_table, name, &empty_entry, NULL);
entry = (GCHandleClassEntry*) sgen_hash_table_lookup (&gchandle_class_hash_table, name);
}
entry->num_handles [handle_type]++;
}
static void
sgen_gchandle_stats_count (void)
{
int i;
sgen_hash_table_clean (&gchandle_class_hash_table);
for (i = HANDLE_TYPE_MIN; i < HANDLE_TYPE_MAX; i++) {
HandleData *handles = gc_handles_for_type ((GCHandleType)i);
SgenArrayList *array = &handles->entries_array;
volatile gpointer *slot;
gpointer hidden, revealed;
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
revealed = MONO_GC_REVEAL_POINTER (hidden, MONO_GC_HANDLE_TYPE_IS_WEAK (i));
if (MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden))
sgen_gchandle_stats_register_vtable (SGEN_LOAD_VTABLE (revealed), i);
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
}
void
sgen_gchandle_stats_report (void)
{
char *name;
GCHandleClassEntry *gchandle_entry;
if (!do_gchandle_stats)
return;
sgen_gchandle_stats_count ();
mono_gc_printf (sgen_gc_debug_file, "\n%-60s %10s %10s %10s\n", "Class", "Normal", "Weak", "Pinned");
SGEN_HASH_TABLE_FOREACH (&gchandle_class_hash_table, char *, name, GCHandleClassEntry *, gchandle_entry) {
mono_gc_printf (sgen_gc_debug_file, "%-60s", name);
mono_gc_printf (sgen_gc_debug_file, " %10ld", (long)gchandle_entry->num_handles [HANDLE_NORMAL]);
size_t weak_handles = gchandle_entry->num_handles [HANDLE_WEAK] +
gchandle_entry->num_handles [HANDLE_WEAK_TRACK] +
gchandle_entry->num_handles [HANDLE_WEAK_FIELDS];
mono_gc_printf (sgen_gc_debug_file, " %10ld", (long)weak_handles);
mono_gc_printf (sgen_gc_debug_file, " %10ld", (long)gchandle_entry->num_handles [HANDLE_PINNED]);
mono_gc_printf (sgen_gc_debug_file, "\n");
} SGEN_HASH_TABLE_FOREACH_END;
}
#endif
void
sgen_init_gchandles (void)
{
#ifdef HEAVY_STATISTICS
mono_counters_register ("GC handles allocated", MONO_COUNTER_GC | MONO_COUNTER_UINT, (void *)&stat_gc_handles_allocated);
mono_counters_register ("max GC handles allocated", MONO_COUNTER_GC | MONO_COUNTER_UINT, (void *)&stat_gc_handles_max_allocated);
#endif
}
#endif
| /**
* \file
* SGen GC handles.
*
* Copyright (C) 2015 Xamarin Inc
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include "config.h"
#ifdef HAVE_SGEN_GC
#include "mono/sgen/sgen-gc.h"
#include "mono/sgen/sgen-client.h"
#include "mono/sgen/sgen-array-list.h"
#include "mono/utils/mono-membar.h"
#ifdef HEAVY_STATISTICS
static volatile guint32 stat_gc_handles_allocated = 0;
static volatile guint32 stat_gc_handles_max_allocated = 0;
#endif
#ifndef DISABLE_SGEN_DEBUG_HELPERS
typedef struct {
size_t num_handles [HANDLE_TYPE_MAX];
} GCHandleClassEntry;
static gboolean do_gchandle_stats = FALSE;
static SgenHashTable gchandle_class_hash_table = SGEN_HASH_TABLE_INIT (INTERNAL_MEM_STATISTICS, INTERNAL_MEM_STAT_GCHANDLE_CLASS, sizeof (GCHandleClassEntry), g_str_hash, g_str_equal);
#endif
/*
* A table of GC handle data, implementing a simple lock-free bitmap allocator.
*
* Each entry in a bucket is a pointer with two tag bits: if
* 'GC_HANDLE_OCCUPIED' returns true for a slot, then the slot is occupied; if
* so, then 'GC_HANDLE_VALID' gives whether the entry refers to a valid (1) or
* NULL (0) object reference. If the reference is valid, then the pointer is an
* object pointer. If the reference is NULL, and 'GC_HANDLE_TYPE_IS_WEAK' is
* true for 'type', then the pointer is a metadata pointer--this allows us to
* retrieve the domain ID of an expired weak reference in Mono.
*/
typedef struct {
SgenArrayList entries_array;
guint8 type;
} HandleData;
static void
protocol_gchandle_update (int handle_type, gpointer link, gpointer old_value, gpointer new_value)
{
gboolean old = MONO_GC_HANDLE_IS_OBJECT_POINTER (old_value);
gboolean new_ = MONO_GC_HANDLE_IS_OBJECT_POINTER (new_value);
gboolean track = handle_type == HANDLE_WEAK_TRACK;
if (!MONO_GC_HANDLE_TYPE_IS_WEAK (handle_type))
return;
if (!old && new_)
sgen_binary_protocol_dislink_add (link, MONO_GC_REVEAL_POINTER (new_value, TRUE), track);
else if (old && !new_)
sgen_binary_protocol_dislink_remove (link, track);
else if (old && new_ && old_value != new_value)
sgen_binary_protocol_dislink_update (link, MONO_GC_REVEAL_POINTER (new_value, TRUE), track);
}
/* Returns the new value in the slot, or NULL if the CAS failed. */
static gpointer
try_set_slot (volatile gpointer *slot, GCObject *obj, gpointer old, GCHandleType type)
{
gpointer new_;
if (obj)
new_ = MONO_GC_HANDLE_OBJECT_POINTER (obj, GC_HANDLE_TYPE_IS_WEAK (type));
else
new_ = MONO_GC_HANDLE_METADATA_POINTER (sgen_client_default_metadata (), GC_HANDLE_TYPE_IS_WEAK (type));
SGEN_ASSERT (0, new_, "Why is the occupied bit not set?");
if (mono_atomic_cas_ptr (slot, new_, old) == old) {
protocol_gchandle_update (type, (gpointer)slot, old, new_);
return new_;
}
return NULL;
}
static gboolean
is_slot_set (volatile gpointer *slot)
{
gpointer entry = *slot;
if (MONO_GC_HANDLE_OCCUPIED (entry))
return TRUE;
return FALSE;
}
/* Try to claim a slot by setting its occupied bit. */
static gboolean
try_occupy_slot (volatile gpointer *slot, gpointer obj, int data)
{
if (is_slot_set (slot))
return FALSE;
return try_set_slot (slot, (GCObject *)obj, NULL, (GCHandleType)data) != NULL;
}
static void
bucket_alloc_callback (gpointer *bucket, guint32 new_bucket_size, gboolean alloc)
{
if (alloc)
sgen_register_root ((char *)bucket, new_bucket_size, SGEN_DESCRIPTOR_NULL, ROOT_TYPE_PINNED, MONO_ROOT_SOURCE_GC_HANDLE, NULL, "GC Handle Bucket (SGen, Pinned)");
else
sgen_deregister_root ((char *)bucket);
}
static void
bucket_alloc_report_root (gpointer *bucket, guint32 new_bucket_size, gboolean alloc)
{
if (alloc)
sgen_client_root_registered ((char *)bucket, new_bucket_size, MONO_ROOT_SOURCE_GC_HANDLE, NULL, "GC Handle Bucket (SGen, Normal)");
else
sgen_client_root_deregistered ((char *)bucket);
}
static HandleData gc_handles [] = {
{ SGEN_ARRAY_LIST_INIT (NULL, is_slot_set, try_occupy_slot, -1), (HANDLE_WEAK) },
{ SGEN_ARRAY_LIST_INIT (NULL, is_slot_set, try_occupy_slot, -1), (HANDLE_WEAK_TRACK) },
{ SGEN_ARRAY_LIST_INIT (bucket_alloc_report_root, is_slot_set, try_occupy_slot, -1), (HANDLE_NORMAL) },
{ SGEN_ARRAY_LIST_INIT (bucket_alloc_callback, is_slot_set, try_occupy_slot, -1), (HANDLE_PINNED) },
{ SGEN_ARRAY_LIST_INIT (NULL, is_slot_set, try_occupy_slot, -1), (HANDLE_WEAK_FIELDS) },
};
static HandleData *
gc_handles_for_type (GCHandleType type)
{
return type < HANDLE_TYPE_MAX ? &gc_handles [type] : NULL;
}
/* This assumes that the world is stopped. */
void
sgen_mark_normal_gc_handles (void *addr, SgenUserMarkFunc mark_func, void *gc_data)
{
HandleData *handles = gc_handles_for_type (HANDLE_NORMAL);
SgenArrayList *array = &handles->entries_array;
volatile gpointer *slot;
gpointer hidden, revealed;
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
revealed = MONO_GC_REVEAL_POINTER (hidden, FALSE);
if (!MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden))
continue;
mark_func ((MonoObject **)&revealed, gc_data);
g_assert (revealed);
*slot = MONO_GC_HANDLE_OBJECT_POINTER (revealed, FALSE);
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
void
sgen_gc_handles_report_roots (SgenUserReportRootFunc report_func, void *gc_data)
{
HandleData *handles = gc_handles_for_type (HANDLE_NORMAL);
SgenArrayList *array = &handles->entries_array;
volatile gpointer *slot;
gpointer hidden, revealed;
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
revealed = MONO_GC_REVEAL_POINTER (hidden, FALSE);
if (MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden))
report_func ((void*)slot, (GCObject*)revealed, gc_data);
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
static guint32
alloc_handle (HandleData *handles, GCObject *obj, gboolean track)
{
guint32 res, index;
SgenArrayList *array = &handles->entries_array;
/*
* If a GC happens shortly after a new bucket is allocated, the entire
* bucket could be scanned even though it's mostly empty. To avoid this,
* we track the maximum index seen so far, so that we can skip the empty
* slots.
*
* Note that we update `next_slot` before we even try occupying the
* slot. If we did it the other way around and a GC happened in
* between, the GC wouldn't know that the slot was occupied. This is
* not a huge deal since `obj` is on the stack and thus pinned anyway,
* but hopefully some day it won't be anymore.
*/
index = sgen_array_list_add (array, obj, handles->type, TRUE);
#ifdef HEAVY_STATISTICS
mono_atomic_inc_i32 ((volatile gint32 *)&stat_gc_handles_allocated);
if (stat_gc_handles_allocated > stat_gc_handles_max_allocated)
stat_gc_handles_max_allocated = stat_gc_handles_allocated;
#endif
/* Ensure that a GC handle cannot be given to another thread without the slot having been set. */
mono_memory_write_barrier ();
res = MONO_GC_HANDLE (index, handles->type);
sgen_client_gchandle_created ((GCHandleType)handles->type, obj, res);
return res;
}
static gboolean
object_older_than (GCObject *object, int generation)
{
return generation == GENERATION_NURSERY && !sgen_ptr_in_nursery (object);
}
/*
* Maps a function over all GC handles.
* This assumes that the world is stopped!
*/
void
sgen_gchandle_iterate (GCHandleType handle_type, int max_generation, SgenGCHandleIterateCallback callback, gpointer user)
{
HandleData *handle_data = gc_handles_for_type (handle_type);
SgenArrayList *array = &handle_data->entries_array;
gpointer hidden, result, occupied;
volatile gpointer *slot;
/* If a new bucket has been allocated, but the capacity has not yet been
* increased, nothing can yet have been allocated in the bucket because the
* world is stopped, so we shouldn't miss any handles during iteration.
*/
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
occupied = (gpointer) MONO_GC_HANDLE_OCCUPIED (hidden);
g_assert (hidden ? !!occupied : !occupied);
if (!occupied)
continue;
result = callback (hidden, handle_type, max_generation, user);
if (result)
SGEN_ASSERT (0, MONO_GC_HANDLE_OCCUPIED (result), "Why did the callback return an unoccupied entry?");
else
HEAVY_STAT (mono_atomic_dec_i32 ((volatile gint32 *)&stat_gc_handles_allocated));
protocol_gchandle_update (handle_type, (gpointer)slot, hidden, result);
*slot = result;
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
guint32
sgen_gchandle_new (GCObject *obj, gboolean pinned)
{
return alloc_handle (gc_handles_for_type (pinned ? HANDLE_PINNED : HANDLE_NORMAL), obj, FALSE);
}
guint32
sgen_gchandle_new_weakref (GCObject *obj, gboolean track_resurrection)
{
return alloc_handle (gc_handles_for_type (track_resurrection ? HANDLE_WEAK_TRACK : HANDLE_WEAK), obj, track_resurrection);
}
static GCObject *
link_get (volatile gpointer *link_addr, gboolean is_weak)
{
void *volatile *link_addr_volatile;
void *ptr;
GCObject *obj;
retry:
link_addr_volatile = link_addr;
ptr = (void*)*link_addr_volatile;
/*
* At this point we have a hidden pointer. If the GC runs
* here, it will not recognize the hidden pointer as a
* reference, and if the object behind it is not referenced
* elsewhere, it will be freed. Once the world is restarted
* we reveal the pointer, giving us a pointer to a freed
* object. To make sure we don't return it, we load the
* hidden pointer again. If it's still the same, we can be
* sure the object reference is valid.
*/
if (ptr && MONO_GC_HANDLE_IS_OBJECT_POINTER (ptr))
obj = (GCObject *)MONO_GC_REVEAL_POINTER (ptr, is_weak);
else
return NULL;
/* Note [dummy use]:
*
* If a GC happens here, obj needs to be on the stack or in a
* register, so we need to prevent this from being reordered
* wrt the check.
*/
sgen_dummy_use (obj);
mono_memory_barrier ();
if (is_weak)
sgen_client_ensure_weak_gchandles_accessible ();
if ((void*)*link_addr_volatile != ptr)
goto retry;
return obj;
}
GCObject*
sgen_gchandle_get_target (guint32 gchandle)
{
guint index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
/* Invalid handles are possible; accessing one should produce NULL. (#34276) */
if (!handles)
return NULL;
return link_get (sgen_array_list_get_slot (&handles->entries_array, index), MONO_GC_HANDLE_TYPE_IS_WEAK (type));
}
void
sgen_gchandle_set_target (guint32 gchandle, GCObject *obj)
{
guint32 index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
volatile gpointer *slot;
gpointer entry;
if (!handles)
return;
slot = sgen_array_list_get_slot (&handles->entries_array, index);
do {
entry = *slot;
SGEN_ASSERT (0, MONO_GC_HANDLE_OCCUPIED (entry), "Why are we setting the target on an unoccupied slot?");
} while (!try_set_slot (slot, obj, entry, (GCHandleType)handles->type));
}
static gpointer
mono_gchandle_slot_metadata (volatile gpointer *slot, gboolean is_weak)
{
gpointer entry;
gpointer metadata;
retry:
entry = *slot;
if (!MONO_GC_HANDLE_OCCUPIED (entry))
return NULL;
if (MONO_GC_HANDLE_IS_OBJECT_POINTER (entry)) {
GCObject *obj = (GCObject *)MONO_GC_REVEAL_POINTER (entry, is_weak);
/* See note [dummy use]. */
sgen_dummy_use (obj);
/*
* FIXME: The compiler could technically not carry a reference to obj around
* at this point and recompute it later, in which case we would still use
* it.
*/
if (*slot != entry)
goto retry;
return sgen_client_metadata_for_object (obj);
}
metadata = MONO_GC_REVEAL_POINTER (entry, is_weak);
/* See note [dummy use]. */
sgen_dummy_use (metadata);
if (*slot != entry)
goto retry;
return metadata;
}
gpointer
sgen_gchandle_get_metadata (guint32 gchandle)
{
guint32 index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
volatile gpointer *slot;
if (!handles)
return NULL;
if (index >= handles->entries_array.capacity)
return NULL;
slot = sgen_array_list_get_slot (&handles->entries_array, index);
return mono_gchandle_slot_metadata (slot, MONO_GC_HANDLE_TYPE_IS_WEAK (type));
}
void
sgen_gchandle_free (guint32 gchandle)
{
if (!gchandle)
return;
guint32 index = MONO_GC_HANDLE_SLOT (gchandle);
GCHandleType type = MONO_GC_HANDLE_TYPE (gchandle);
HandleData *handles = gc_handles_for_type (type);
volatile gpointer *slot;
gpointer entry;
if (!handles)
return;
slot = sgen_array_list_get_slot (&handles->entries_array, index);
entry = *slot;
if (index < handles->entries_array.capacity && MONO_GC_HANDLE_OCCUPIED (entry)) {
*slot = NULL;
protocol_gchandle_update (handles->type, (gpointer)slot, entry, NULL);
HEAVY_STAT (mono_atomic_dec_i32 ((volatile gint32 *)&stat_gc_handles_allocated));
} else {
/* print a warning? */
}
sgen_client_gchandle_destroyed ((GCHandleType)handles->type, gchandle);
}
/*
* Returns whether to remove the link from its hash.
*/
static gpointer
null_link_if_necessary (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user)
{
const gboolean is_weak = GC_HANDLE_TYPE_IS_WEAK (handle_type);
ScanCopyContext *ctx = (ScanCopyContext *)user;
GCObject *obj;
GCObject *copy;
if (!MONO_GC_HANDLE_VALID (hidden))
return hidden;
obj = (GCObject *)MONO_GC_REVEAL_POINTER (hidden, MONO_GC_HANDLE_TYPE_IS_WEAK (handle_type));
SGEN_ASSERT (0, obj, "Why is the hidden pointer NULL?");
if (object_older_than (obj, max_generation))
return hidden;
if (sgen_major_collector.is_object_live (obj))
return hidden;
/* Clear link if object is ready for finalization. This check may be redundant wrt is_object_live(). */
if (sgen_gc_is_object_ready_for_finalization (obj))
return MONO_GC_HANDLE_METADATA_POINTER (sgen_client_metadata_for_object (obj), is_weak);
copy = obj;
ctx->ops->copy_or_mark_object (©, ctx->queue);
SGEN_ASSERT (0, copy, "Why couldn't we copy the object?");
/* Update link if object was moved. */
return MONO_GC_HANDLE_OBJECT_POINTER (copy, is_weak);
}
static gpointer
scan_for_weak (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user)
{
const gboolean is_weak = GC_HANDLE_TYPE_IS_WEAK (handle_type);
ScanCopyContext *ctx = (ScanCopyContext *)user;
if (!MONO_GC_HANDLE_VALID (hidden))
return hidden;
GCObject *obj = (GCObject *)MONO_GC_REVEAL_POINTER (hidden, is_weak);
/* If the object is dead we free the gc handle */
if (!sgen_is_object_alive_for_current_gen (obj))
return NULL;
/* Relocate it */
ctx->ops->copy_or_mark_object (&obj, ctx->queue);
int nbits;
gsize *weak_bitmap = sgen_client_get_weak_bitmap (SGEN_LOAD_VTABLE (obj), &nbits);
for (int i = 0; i < nbits; ++i) {
if (weak_bitmap [i / (sizeof (gsize) * 8)] & ((gsize)1 << (i % (sizeof (gsize) * 8)))) {
GCObject **addr = (GCObject **)((char*)obj + (i * sizeof (gpointer)));
GCObject *field = *addr;
/* if the object in the weak field is alive, we relocate it */
if (field && sgen_is_object_alive_for_current_gen (field))
ctx->ops->copy_or_mark_object (addr, ctx->queue);
else
*addr = NULL;
}
}
/* Update link if object was moved. */
return MONO_GC_HANDLE_OBJECT_POINTER (obj, is_weak);
}
/* LOCKING: requires that the GC lock is held */
void
sgen_null_link_in_range (int generation, ScanCopyContext ctx, gboolean track)
{
sgen_gchandle_iterate (track ? HANDLE_WEAK_TRACK : HANDLE_WEAK, generation, null_link_if_necessary, &ctx);
//we're always called for gen zero. !track means short ref
if (generation == 0 && !track)
sgen_gchandle_iterate (HANDLE_WEAK_FIELDS, generation, scan_for_weak, &ctx);
}
typedef struct {
SgenObjectPredicateFunc predicate;
gpointer data;
} WeakLinkAlivePredicateClosure;
static gpointer
null_link_if (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user)
{
WeakLinkAlivePredicateClosure *closure = (WeakLinkAlivePredicateClosure *)user;
GCObject *obj;
if (!MONO_GC_HANDLE_VALID (hidden))
return hidden;
obj = (GCObject *)MONO_GC_REVEAL_POINTER (hidden, MONO_GC_HANDLE_TYPE_IS_WEAK (handle_type));
SGEN_ASSERT (0, obj, "Why is the hidden pointer NULL?");
if (object_older_than (obj, max_generation))
return hidden;
if (closure->predicate (obj, closure->data))
return MONO_GC_HANDLE_METADATA_POINTER (sgen_client_default_metadata (), GC_HANDLE_TYPE_IS_WEAK (handle_type));
return hidden;
}
/* LOCKING: requires that the GC lock is held */
void
sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track)
{
WeakLinkAlivePredicateClosure closure = { predicate, data };
sgen_gchandle_iterate (track ? HANDLE_WEAK_TRACK : HANDLE_WEAK, generation, null_link_if, &closure);
}
void
sgen_register_obj_with_weak_fields (GCObject *obj)
{
//
// We use a gc handle to be able to do some processing for these objects at every gc
//
alloc_handle (gc_handles_for_type (HANDLE_WEAK_FIELDS), obj, FALSE);
}
#ifndef DISABLE_SGEN_DEBUG_HELPERS
void
sgen_gchandle_stats_enable (void)
{
do_gchandle_stats = TRUE;
}
static void
sgen_gchandle_stats_register_vtable (GCVTable vtable, int handle_type)
{
GCHandleClassEntry *entry;
char *name = g_strdup_printf ("%s.%s", sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable));
entry = (GCHandleClassEntry*) sgen_hash_table_lookup (&gchandle_class_hash_table, name);
if (entry) {
g_free (name);
} else {
// Create the entry for this class and get the address of it
GCHandleClassEntry empty_entry;
memset (&empty_entry, 0, sizeof (GCHandleClassEntry));
sgen_hash_table_replace (&gchandle_class_hash_table, name, &empty_entry, NULL);
entry = (GCHandleClassEntry*) sgen_hash_table_lookup (&gchandle_class_hash_table, name);
}
entry->num_handles [handle_type]++;
}
static void
sgen_gchandle_stats_count (void)
{
int i;
sgen_hash_table_clean (&gchandle_class_hash_table);
for (i = HANDLE_TYPE_MIN; i < HANDLE_TYPE_MAX; i++) {
HandleData *handles = gc_handles_for_type ((GCHandleType)i);
SgenArrayList *array = &handles->entries_array;
volatile gpointer *slot;
gpointer hidden, revealed;
SGEN_ARRAY_LIST_FOREACH_SLOT (array, slot) {
hidden = *slot;
revealed = MONO_GC_REVEAL_POINTER (hidden, MONO_GC_HANDLE_TYPE_IS_WEAK (i));
if (MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden))
sgen_gchandle_stats_register_vtable (SGEN_LOAD_VTABLE (revealed), i);
} SGEN_ARRAY_LIST_END_FOREACH_SLOT;
}
}
void
sgen_gchandle_stats_report (void)
{
char *name;
GCHandleClassEntry *gchandle_entry;
if (!do_gchandle_stats)
return;
sgen_gchandle_stats_count ();
mono_gc_printf (sgen_gc_debug_file, "\n%-60s %10s %10s %10s\n", "Class", "Normal", "Weak", "Pinned");
SGEN_HASH_TABLE_FOREACH (&gchandle_class_hash_table, char *, name, GCHandleClassEntry *, gchandle_entry) {
mono_gc_printf (sgen_gc_debug_file, "%-60s", name);
mono_gc_printf (sgen_gc_debug_file, " %10ld", (long)gchandle_entry->num_handles [HANDLE_NORMAL]);
size_t weak_handles = gchandle_entry->num_handles [HANDLE_WEAK] +
gchandle_entry->num_handles [HANDLE_WEAK_TRACK] +
gchandle_entry->num_handles [HANDLE_WEAK_FIELDS];
mono_gc_printf (sgen_gc_debug_file, " %10ld", (long)weak_handles);
mono_gc_printf (sgen_gc_debug_file, " %10ld", (long)gchandle_entry->num_handles [HANDLE_PINNED]);
mono_gc_printf (sgen_gc_debug_file, "\n");
} SGEN_HASH_TABLE_FOREACH_END;
}
#endif
void
sgen_init_gchandles (void)
{
#ifdef HEAVY_STATISTICS
mono_counters_register ("GC handles allocated", MONO_COUNTER_GC | MONO_COUNTER_UINT, (void *)&stat_gc_handles_allocated);
mono_counters_register ("max GC handles allocated", MONO_COUNTER_GC | MONO_COUNTER_UINT, (void *)&stat_gc_handles_max_allocated);
#endif
}
#endif
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/coreclr/pal/src/libunwind/doc/libunwind.man | '\" t
.\" Manual page created with latex2man on Thu Jan 12 06:50:29 PST 2017
.\" NOTE: This file is generated, DO NOT EDIT.
.de Vb
.ft CW
.nf
..
.de Ve
.ft R
.fi
..
.TH "LIBUNWIND" "3" "12 January 2017" "Programming Library " "Programming Library "
.SH NAME
libunwind
\-\- a (mostly) platform\-independent unwind API
.PP
.SH SYNOPSIS
.PP
#include <libunwind.h>
.br
.PP
int
unw_getcontext(unw_context_t *);
.br
int
unw_init_local(unw_cursor_t *,
unw_context_t *);
.br
int
unw_init_remote(unw_cursor_t *,
unw_addr_space_t,
void *);
.br
int
unw_step(unw_cursor_t *);
.br
int
unw_get_reg(unw_cursor_t *,
unw_regnum_t,
unw_word_t *);
.br
int
unw_get_fpreg(unw_cursor_t *,
unw_regnum_t,
unw_fpreg_t *);
.br
int
unw_set_reg(unw_cursor_t *,
unw_regnum_t,
unw_word_t);
.br
int
unw_set_fpreg(unw_cursor_t *,
unw_regnum_t,
unw_fpreg_t);
.br
int
unw_resume(unw_cursor_t *);
.br
.PP
unw_addr_space_t
unw_local_addr_space;
.br
unw_addr_space_t
unw_create_addr_space(unw_accessors_t,
int);
.br
void
unw_destroy_addr_space(unw_addr_space_t);
.br
unw_accessors_t
unw_get_accessors(unw_addr_space_t);
.br
void
unw_flush_cache(unw_addr_space_t,
unw_word_t,
unw_word_t);
.br
int
unw_set_caching_policy(unw_addr_space_t,
unw_caching_policy_t);
.br
int
unw_set_cache_size(unw_addr_space_t,
size_t,
int);
.br
.PP
const char *unw_regname(unw_regnum_t);
.br
int
unw_get_proc_info(unw_cursor_t *,
unw_proc_info_t *);
.br
int
unw_get_save_loc(unw_cursor_t *,
int,
unw_save_loc_t *);
.br
int
unw_is_fpreg(unw_regnum_t);
.br
int
unw_is_signal_frame(unw_cursor_t *);
.br
int
unw_get_proc_name(unw_cursor_t *,
char *,
size_t,
unw_word_t *);
.br
.PP
void
_U_dyn_register(unw_dyn_info_t *);
.br
void
_U_dyn_cancel(unw_dyn_info_t *);
.br
.PP
.SH LOCAL UNWINDING
.PP
Libunwind
is very easy to use when unwinding a stack from
within a running program. This is called \fIlocal\fP
unwinding. Say
you want to unwind the stack while executing in some function
F().
In this function, you would call unw_getcontext()
to get a snapshot of the CPU registers (machine\-state). Then you
initialize an \fIunwind cursor\fP
based on this snapshot. This is
done with a call to unw_init_local().
The cursor now points
to the current frame, that is, the stack frame that corresponds to the
current activation of function F().
The unwind cursor can then
be moved ``up\&'' (towards earlier stack frames) by calling
unw_step().
By repeatedly calling this routine, you can
uncover the entire call\-chain that led to the activation of function
F().
A positive return value from unw_step()
indicates
that there are more frames in the chain, zero indicates that the end
of the chain has been reached, and any negative value indicates that
some sort of error has occurred.
.PP
While it is not possible to directly move the unwind cursor in the
``down\&'' direction (towards newer stack frames), this effect can be
achieved by making copies of an unwind cursor. For example, a program
that sometimes has to move ``down\&'' by one stack frame could maintain
two cursor variables: ``curr\&''
and ``prev\&''\&.
The former
would be used as the current cursor and prev
would be maintained
as the ``previous frame\&'' cursor by copying the contents of curr
to prev
right before calling unw_step().
With this
approach, the program could move one step ``down\&'' simply by copying
back prev
to curr
whenever that is necessary. In the most
extreme case, a program could maintain a separate cursor for each call
frame and that way it could move up and down the callframe\-chain at
will.
.PP
Given an unwind cursor, it is possible to read and write the CPU
registers that were preserved for the current stack frame (as
identified by the cursor). Libunwind
provides several routines
for this purpose: unw_get_reg()
reads an integer (general)
register, unw_get_fpreg()
reads a floating\-point register,
unw_set_reg()
writes an integer register, and
unw_set_fpreg()
writes a floating\-point register. Note that,
by definition, only the \fIpreserved\fP
machine state can be accessed
during an unwind operation. Normally, this state consists of the
\fIcallee\-saved\fP
(``preserved\&'') registers. However, in some
special circumstances (e.g., in a signal handler trampoline), even the
\fIcaller\-saved\fP
(``scratch\&'') registers are preserved in the stack
frame and, in those cases, libunwind
will grant access to them
as well. The exact set of registers that can be accessed via the
cursor depends, of course, on the platform. However, there are two
registers that can be read on all platforms: the instruction pointer
(IP), sometimes also known as the ``program counter\&'', and the stack
pointer (SP). In libunwind,
these registers are identified by
the macros UNW_REG_IP
and UNW_REG_SP,
respectively.
.PP
Besides just moving the unwind cursor and reading/writing saved
registers, libunwind
also provides the ability to resume
execution at an arbitrary stack frame. As you might guess, this is
useful for implementing non\-local gotos and the exception handling
needed by some high\-level languages such as Java. Resuming execution
with a particular stack frame simply requires calling
unw_resume()
and passing the cursor identifying the target
frame as the only argument.
.PP
Normally, libunwind
supports both local and remote unwinding
(the latter will be explained in the next section). However, if you
tell libunwind that your program only needs local unwinding, then a
special implementation can be selected which may run much faster than
the generic implementation which supports both kinds of unwinding. To
select this optimized version, simply define the macro
UNW_LOCAL_ONLY
before including the headerfile
<libunwind.h>\&.
It is perfectly OK for a single program to
employ both local\-only and generic unwinding. That is, whether or not
UNW_LOCAL_ONLY
is defined is a choice that each source\-file
(compilation\-unit) can make on its own. Independent of the setting(s)
of UNW_LOCAL_ONLY,
you\&'ll always link the same library into
the program (normally \fB\-l\fPunwind).
Furthermore, the
portion of libunwind
that manages unwind\-info for dynamically
generated code is not affected by the setting of
UNW_LOCAL_ONLY\&.
.PP
If we put all of the above together, here is how we could use
libunwind
to write a function ``show_backtrace()\&''
which prints a classic stack trace:
.PP
.Vb
#define UNW_LOCAL_ONLY
#include <libunwind.h>
void show_backtrace (void) {
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
printf ("ip = %lx, sp = %lx\\n", (long) ip, (long) sp);
}
}
.Ve
.PP
.SH REMOTE UNWINDING
.PP
Libunwind
can also be used to unwind a stack in a ``remote\&''
process. Here, ``remote\&'' may mean another process on the same
machine or even a process on a completely different machine from the
one that is running libunwind\&.
Remote unwinding is typically
used by debuggers and instruction\-set simulators, for example.
.PP
Before you can unwind a remote process, you need to create a new
address\-space object for that process. This is achieved with the
unw_create_addr_space()
routine. The routine takes two
arguments: a pointer to a set of \fIaccessor\fP
routines and an
integer that specifies the byte\-order of the target process. The
accessor routines provide libunwind
with the means to
communicate with the remote process. In particular, there are
callbacks to read and write the process\&'s memory, its registers, and
to access unwind information which may be needed by libunwind\&.
.PP
With the address space created, unwinding can be initiated by a call
to unw_init_remote().
This routine is very similar to
unw_init_local(),
except that it takes an address\-space
object and an opaque pointer as arguments. The routine uses these
arguments to fetch the initial machine state. Libunwind
never
uses the opaque pointer on its own, but instead just passes it on to
the accessor (callback) routines. Typically, this pointer is used to
select, e.g., the thread within a process that is to be unwound.
.PP
Once a cursor has been initialized with unw_init_remote(),
unwinding works exactly like in the local case. That is, you can use
unw_step()
to move ``up\&'' in the call\-chain, read and write
registers, or resume execution at a particular stack frame by calling
unw_resume\&.
.PP
.SH CROSS\-PLATFORM AND MULTI\-PLATFORM UNWINDING
.PP
Libunwind
has been designed to enable unwinding across
platforms (architectures). Indeed, a single program can use
libunwind
to unwind an arbitrary number of target platforms,
all at the same time!
.PP
We call the machine that is running libunwind
the \fIhost\fP
and the machine that is running the process being unwound the
\fItarget\fP\&.
If the host and the target platform are the same, we
call it \fInative\fP
unwinding. If they differ, we call it
\fIcross\-platform\fP
unwinding.
.PP
The principle behind supporting native, cross\-platform, and
multi\-platform unwinding is very simple: for native unwinding, a
program includes <libunwind.h>
and uses the linker switch
\fB\-l\fPunwind\&.
For cross\-platform unwinding, a program
includes <libunwind\-PLAT\&.h>
and uses the linker
switch \fB\-l\fPunwind\-PLAT,
where PLAT
is the name
of the target platform (e.g., ia64
for IA\-64, hppa\-elf
for ELF\-based HP PA\-RISC, or x86
for 80386). Multi\-platform
unwinding works exactly like cross\-platform unwinding, the only
limitation is that a single source file (compilation unit) can include
at most one libunwind
header file. In other words, the
platform\-specific support for each supported target needs to be
isolated in separate source files\-\-\-a limitation that shouldn\&'t be an
issue in practice.
.PP
Note that, by definition, local unwinding is possible only for the
native case. Attempting to call, e.g., unw_local_init()
when
targeting a cross\-platform will result in a link\-time error
(unresolved references).
.PP
.SH THREAD\- AND SIGNAL\-SAFETY
.PP
All libunwind
routines are thread\-safe. What this means is
that multiple threads may use libunwind
simulatenously.
However, any given cursor may be accessed by only one thread at
any given time.
.PP
To ensure thread\-safety, some libunwind
routines may have to
use locking. Such routines \fImust not\fP
be called from signal
handlers (directly or indirectly) and are therefore \fInot\fP
signal\-safe. The manual page for each libunwind
routine
identifies whether or not it is signal\-safe, but as a general rule,
any routine that may be needed for \fIlocal\fP
unwinding is
signal\-safe (e.g., unw_step()
for local unwinding is
signal\-safe). For remote\-unwinding, \fInone\fP
of the
libunwind
routines are guaranteed to be signal\-safe.
.PP
.SH UNWINDING THROUGH DYNAMICALLY GENERATED CODE
.PP
Libunwind
provides the routines _U_dyn_register()
and
_U_dyn_cancel()
to register/cancel the information required to
unwind through code that has been generated at runtime (e.g., by a
just\-in\-time (JIT) compiler). It is important to register the
information for \fIall\fP
dynamically generated code because
otherwise, a debugger may not be able to function properly or
high\-level language exception handling may not work as expected.
.PP
The interface for registering and canceling dynamic unwind info has
been designed for maximum efficiency, so as to minimize the
performance impact on JIT\-compilers. In particular, both routines are
guaranteed to execute in ``constant time\&'' (O(1)) and the
data\-structure encapsulating the dynamic unwind info has been designed
to facilitate sharing, such that similar procedures can share much of
the underlying information.
.PP
For more information on the libunwind
support for dynamically
generated code, see libunwind\-dynamic(3)\&.
.PP
.SH CACHING OF UNWIND INFO
.PP
To speed up execution, libunwind
may aggressively cache the
information it needs to perform unwinding. If a process changes
during its lifetime, this creates a risk of libunwind
using
stale data. For example, this would happen if libunwind
were
to cache information about a shared library which later on gets
unloaded (e.g., via \fIdlclose\fP(3)).
.PP
To prevent the risk of using stale data, libunwind
provides two
facilities: first, it is possible to flush the cached information
associated with a specific address range in the target process (or the
entire address space, if desired). This functionality is provided by
unw_flush_cache().
The second facility is provided by
unw_set_caching_policy(),
which lets a program
select the exact caching policy in use for a given address\-space
object. In particular, by selecting the policy
UNW_CACHE_NONE,
it is possible to turn off caching
completely, therefore eliminating the risk of stale data alltogether
(at the cost of slower execution). By default, caching is enabled for
local unwinding only. The cache size can be dynamically changed with
unw_set_cache_size(),
which also fluches the current cache.
.PP
.SH FILES
.PP
.TP
libunwind.h
Headerfile to include for native (same
platform) unwinding.
.TP
libunwind\-PLAT\&.h
Headerfile to include when
the unwind target runs on platform PLAT\&.
For example, to unwind
an IA\-64 program, the header file libunwind\-ia64.h
should be
included.
.TP
\fB\-l\fPunwind
Linker\-switch to add when building a
program that does native (same platform) unwinding.
.TP
\fB\-l\fPunwind\-PLAT
Linker\-switch to add when
building a program that unwinds a program on platform PLAT\&.
For example, to (cross\-)unwind an IA\-64 program, the linker switch
\-lunwind\-ia64
should be added. Note: multiple such switches
may need to be specified for programs that can unwind programs on
multiple platforms.
.PP
.SH SEE ALSO
.PP
libunwind\-dynamic(3),
libunwind\-ia64(3),
libunwind\-ptrace(3),
libunwind\-setjmp(3),
unw_create_addr_space(3),
unw_destroy_addr_space(3),
unw_flush_cache(3),
unw_get_accessors(3),
unw_get_fpreg(3),
unw_get_proc_info(3),
unw_get_proc_name(3),
unw_get_reg(3),
unw_getcontext(3),
unw_init_local(3),
unw_init_remote(3),
unw_is_fpreg(3),
unw_is_signal_frame(3),
unw_regname(3),
unw_resume(3),
unw_set_caching_policy(3),
unw_set_cache_size(3),
unw_set_fpreg(3),
unw_set_reg(3),
unw_step(3),
unw_strerror(3),
_U_dyn_register(3),
_U_dyn_cancel(3)
.PP
.SH AUTHOR
.PP
David Mosberger\-Tang
.br
Email: \[email protected]\fP
.br
WWW: \fBhttp://www.nongnu.org/libunwind/\fP\&.
.\" NOTE: This file is generated, DO NOT EDIT.
| '\" t
.\" Manual page created with latex2man on Thu Jan 12 06:50:29 PST 2017
.\" NOTE: This file is generated, DO NOT EDIT.
.de Vb
.ft CW
.nf
..
.de Ve
.ft R
.fi
..
.TH "LIBUNWIND" "3" "12 January 2017" "Programming Library " "Programming Library "
.SH NAME
libunwind
\-\- a (mostly) platform\-independent unwind API
.PP
.SH SYNOPSIS
.PP
#include <libunwind.h>
.br
.PP
int
unw_getcontext(unw_context_t *);
.br
int
unw_init_local(unw_cursor_t *,
unw_context_t *);
.br
int
unw_init_remote(unw_cursor_t *,
unw_addr_space_t,
void *);
.br
int
unw_step(unw_cursor_t *);
.br
int
unw_get_reg(unw_cursor_t *,
unw_regnum_t,
unw_word_t *);
.br
int
unw_get_fpreg(unw_cursor_t *,
unw_regnum_t,
unw_fpreg_t *);
.br
int
unw_set_reg(unw_cursor_t *,
unw_regnum_t,
unw_word_t);
.br
int
unw_set_fpreg(unw_cursor_t *,
unw_regnum_t,
unw_fpreg_t);
.br
int
unw_resume(unw_cursor_t *);
.br
.PP
unw_addr_space_t
unw_local_addr_space;
.br
unw_addr_space_t
unw_create_addr_space(unw_accessors_t,
int);
.br
void
unw_destroy_addr_space(unw_addr_space_t);
.br
unw_accessors_t
unw_get_accessors(unw_addr_space_t);
.br
void
unw_flush_cache(unw_addr_space_t,
unw_word_t,
unw_word_t);
.br
int
unw_set_caching_policy(unw_addr_space_t,
unw_caching_policy_t);
.br
int
unw_set_cache_size(unw_addr_space_t,
size_t,
int);
.br
.PP
const char *unw_regname(unw_regnum_t);
.br
int
unw_get_proc_info(unw_cursor_t *,
unw_proc_info_t *);
.br
int
unw_get_save_loc(unw_cursor_t *,
int,
unw_save_loc_t *);
.br
int
unw_is_fpreg(unw_regnum_t);
.br
int
unw_is_signal_frame(unw_cursor_t *);
.br
int
unw_get_proc_name(unw_cursor_t *,
char *,
size_t,
unw_word_t *);
.br
.PP
void
_U_dyn_register(unw_dyn_info_t *);
.br
void
_U_dyn_cancel(unw_dyn_info_t *);
.br
.PP
.SH LOCAL UNWINDING
.PP
Libunwind
is very easy to use when unwinding a stack from
within a running program. This is called \fIlocal\fP
unwinding. Say
you want to unwind the stack while executing in some function
F().
In this function, you would call unw_getcontext()
to get a snapshot of the CPU registers (machine\-state). Then you
initialize an \fIunwind cursor\fP
based on this snapshot. This is
done with a call to unw_init_local().
The cursor now points
to the current frame, that is, the stack frame that corresponds to the
current activation of function F().
The unwind cursor can then
be moved ``up\&'' (towards earlier stack frames) by calling
unw_step().
By repeatedly calling this routine, you can
uncover the entire call\-chain that led to the activation of function
F().
A positive return value from unw_step()
indicates
that there are more frames in the chain, zero indicates that the end
of the chain has been reached, and any negative value indicates that
some sort of error has occurred.
.PP
While it is not possible to directly move the unwind cursor in the
``down\&'' direction (towards newer stack frames), this effect can be
achieved by making copies of an unwind cursor. For example, a program
that sometimes has to move ``down\&'' by one stack frame could maintain
two cursor variables: ``curr\&''
and ``prev\&''\&.
The former
would be used as the current cursor and prev
would be maintained
as the ``previous frame\&'' cursor by copying the contents of curr
to prev
right before calling unw_step().
With this
approach, the program could move one step ``down\&'' simply by copying
back prev
to curr
whenever that is necessary. In the most
extreme case, a program could maintain a separate cursor for each call
frame and that way it could move up and down the callframe\-chain at
will.
.PP
Given an unwind cursor, it is possible to read and write the CPU
registers that were preserved for the current stack frame (as
identified by the cursor). Libunwind
provides several routines
for this purpose: unw_get_reg()
reads an integer (general)
register, unw_get_fpreg()
reads a floating\-point register,
unw_set_reg()
writes an integer register, and
unw_set_fpreg()
writes a floating\-point register. Note that,
by definition, only the \fIpreserved\fP
machine state can be accessed
during an unwind operation. Normally, this state consists of the
\fIcallee\-saved\fP
(``preserved\&'') registers. However, in some
special circumstances (e.g., in a signal handler trampoline), even the
\fIcaller\-saved\fP
(``scratch\&'') registers are preserved in the stack
frame and, in those cases, libunwind
will grant access to them
as well. The exact set of registers that can be accessed via the
cursor depends, of course, on the platform. However, there are two
registers that can be read on all platforms: the instruction pointer
(IP), sometimes also known as the ``program counter\&'', and the stack
pointer (SP). In libunwind,
these registers are identified by
the macros UNW_REG_IP
and UNW_REG_SP,
respectively.
.PP
Besides just moving the unwind cursor and reading/writing saved
registers, libunwind
also provides the ability to resume
execution at an arbitrary stack frame. As you might guess, this is
useful for implementing non\-local gotos and the exception handling
needed by some high\-level languages such as Java. Resuming execution
with a particular stack frame simply requires calling
unw_resume()
and passing the cursor identifying the target
frame as the only argument.
.PP
Normally, libunwind
supports both local and remote unwinding
(the latter will be explained in the next section). However, if you
tell libunwind that your program only needs local unwinding, then a
special implementation can be selected which may run much faster than
the generic implementation which supports both kinds of unwinding. To
select this optimized version, simply define the macro
UNW_LOCAL_ONLY
before including the headerfile
<libunwind.h>\&.
It is perfectly OK for a single program to
employ both local\-only and generic unwinding. That is, whether or not
UNW_LOCAL_ONLY
is defined is a choice that each source\-file
(compilation\-unit) can make on its own. Independent of the setting(s)
of UNW_LOCAL_ONLY,
you\&'ll always link the same library into
the program (normally \fB\-l\fPunwind).
Furthermore, the
portion of libunwind
that manages unwind\-info for dynamically
generated code is not affected by the setting of
UNW_LOCAL_ONLY\&.
.PP
If we put all of the above together, here is how we could use
libunwind
to write a function ``show_backtrace()\&''
which prints a classic stack trace:
.PP
.Vb
#define UNW_LOCAL_ONLY
#include <libunwind.h>
void show_backtrace (void) {
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
printf ("ip = %lx, sp = %lx\\n", (long) ip, (long) sp);
}
}
.Ve
.PP
.SH REMOTE UNWINDING
.PP
Libunwind
can also be used to unwind a stack in a ``remote\&''
process. Here, ``remote\&'' may mean another process on the same
machine or even a process on a completely different machine from the
one that is running libunwind\&.
Remote unwinding is typically
used by debuggers and instruction\-set simulators, for example.
.PP
Before you can unwind a remote process, you need to create a new
address\-space object for that process. This is achieved with the
unw_create_addr_space()
routine. The routine takes two
arguments: a pointer to a set of \fIaccessor\fP
routines and an
integer that specifies the byte\-order of the target process. The
accessor routines provide libunwind
with the means to
communicate with the remote process. In particular, there are
callbacks to read and write the process\&'s memory, its registers, and
to access unwind information which may be needed by libunwind\&.
.PP
With the address space created, unwinding can be initiated by a call
to unw_init_remote().
This routine is very similar to
unw_init_local(),
except that it takes an address\-space
object and an opaque pointer as arguments. The routine uses these
arguments to fetch the initial machine state. Libunwind
never
uses the opaque pointer on its own, but instead just passes it on to
the accessor (callback) routines. Typically, this pointer is used to
select, e.g., the thread within a process that is to be unwound.
.PP
Once a cursor has been initialized with unw_init_remote(),
unwinding works exactly like in the local case. That is, you can use
unw_step()
to move ``up\&'' in the call\-chain, read and write
registers, or resume execution at a particular stack frame by calling
unw_resume\&.
.PP
.SH CROSS\-PLATFORM AND MULTI\-PLATFORM UNWINDING
.PP
Libunwind
has been designed to enable unwinding across
platforms (architectures). Indeed, a single program can use
libunwind
to unwind an arbitrary number of target platforms,
all at the same time!
.PP
We call the machine that is running libunwind
the \fIhost\fP
and the machine that is running the process being unwound the
\fItarget\fP\&.
If the host and the target platform are the same, we
call it \fInative\fP
unwinding. If they differ, we call it
\fIcross\-platform\fP
unwinding.
.PP
The principle behind supporting native, cross\-platform, and
multi\-platform unwinding is very simple: for native unwinding, a
program includes <libunwind.h>
and uses the linker switch
\fB\-l\fPunwind\&.
For cross\-platform unwinding, a program
includes <libunwind\-PLAT\&.h>
and uses the linker
switch \fB\-l\fPunwind\-PLAT,
where PLAT
is the name
of the target platform (e.g., ia64
for IA\-64, hppa\-elf
for ELF\-based HP PA\-RISC, or x86
for 80386). Multi\-platform
unwinding works exactly like cross\-platform unwinding, the only
limitation is that a single source file (compilation unit) can include
at most one libunwind
header file. In other words, the
platform\-specific support for each supported target needs to be
isolated in separate source files\-\-\-a limitation that shouldn\&'t be an
issue in practice.
.PP
Note that, by definition, local unwinding is possible only for the
native case. Attempting to call, e.g., unw_local_init()
when
targeting a cross\-platform will result in a link\-time error
(unresolved references).
.PP
.SH THREAD\- AND SIGNAL\-SAFETY
.PP
All libunwind
routines are thread\-safe. What this means is
that multiple threads may use libunwind
simulatenously.
However, any given cursor may be accessed by only one thread at
any given time.
.PP
To ensure thread\-safety, some libunwind
routines may have to
use locking. Such routines \fImust not\fP
be called from signal
handlers (directly or indirectly) and are therefore \fInot\fP
signal\-safe. The manual page for each libunwind
routine
identifies whether or not it is signal\-safe, but as a general rule,
any routine that may be needed for \fIlocal\fP
unwinding is
signal\-safe (e.g., unw_step()
for local unwinding is
signal\-safe). For remote\-unwinding, \fInone\fP
of the
libunwind
routines are guaranteed to be signal\-safe.
.PP
.SH UNWINDING THROUGH DYNAMICALLY GENERATED CODE
.PP
Libunwind
provides the routines _U_dyn_register()
and
_U_dyn_cancel()
to register/cancel the information required to
unwind through code that has been generated at runtime (e.g., by a
just\-in\-time (JIT) compiler). It is important to register the
information for \fIall\fP
dynamically generated code because
otherwise, a debugger may not be able to function properly or
high\-level language exception handling may not work as expected.
.PP
The interface for registering and canceling dynamic unwind info has
been designed for maximum efficiency, so as to minimize the
performance impact on JIT\-compilers. In particular, both routines are
guaranteed to execute in ``constant time\&'' (O(1)) and the
data\-structure encapsulating the dynamic unwind info has been designed
to facilitate sharing, such that similar procedures can share much of
the underlying information.
.PP
For more information on the libunwind
support for dynamically
generated code, see libunwind\-dynamic(3)\&.
.PP
.SH CACHING OF UNWIND INFO
.PP
To speed up execution, libunwind
may aggressively cache the
information it needs to perform unwinding. If a process changes
during its lifetime, this creates a risk of libunwind
using
stale data. For example, this would happen if libunwind
were
to cache information about a shared library which later on gets
unloaded (e.g., via \fIdlclose\fP(3)).
.PP
To prevent the risk of using stale data, libunwind
provides two
facilities: first, it is possible to flush the cached information
associated with a specific address range in the target process (or the
entire address space, if desired). This functionality is provided by
unw_flush_cache().
The second facility is provided by
unw_set_caching_policy(),
which lets a program
select the exact caching policy in use for a given address\-space
object. In particular, by selecting the policy
UNW_CACHE_NONE,
it is possible to turn off caching
completely, therefore eliminating the risk of stale data alltogether
(at the cost of slower execution). By default, caching is enabled for
local unwinding only. The cache size can be dynamically changed with
unw_set_cache_size(),
which also fluches the current cache.
.PP
.SH FILES
.PP
.TP
libunwind.h
Headerfile to include for native (same
platform) unwinding.
.TP
libunwind\-PLAT\&.h
Headerfile to include when
the unwind target runs on platform PLAT\&.
For example, to unwind
an IA\-64 program, the header file libunwind\-ia64.h
should be
included.
.TP
\fB\-l\fPunwind
Linker\-switch to add when building a
program that does native (same platform) unwinding.
.TP
\fB\-l\fPunwind\-PLAT
Linker\-switch to add when
building a program that unwinds a program on platform PLAT\&.
For example, to (cross\-)unwind an IA\-64 program, the linker switch
\-lunwind\-ia64
should be added. Note: multiple such switches
may need to be specified for programs that can unwind programs on
multiple platforms.
.PP
.SH SEE ALSO
.PP
libunwind\-dynamic(3),
libunwind\-ia64(3),
libunwind\-ptrace(3),
libunwind\-setjmp(3),
unw_create_addr_space(3),
unw_destroy_addr_space(3),
unw_flush_cache(3),
unw_get_accessors(3),
unw_get_fpreg(3),
unw_get_proc_info(3),
unw_get_proc_name(3),
unw_get_reg(3),
unw_getcontext(3),
unw_init_local(3),
unw_init_remote(3),
unw_is_fpreg(3),
unw_is_signal_frame(3),
unw_regname(3),
unw_resume(3),
unw_set_caching_policy(3),
unw_set_cache_size(3),
unw_set_fpreg(3),
unw_set_reg(3),
unw_step(3),
unw_strerror(3),
_U_dyn_register(3),
_U_dyn_cancel(3)
.PP
.SH AUTHOR
.PP
David Mosberger\-Tang
.br
Email: \[email protected]\fP
.br
WWW: \fBhttp://www.nongnu.org/libunwind/\fP\&.
.\" NOTE: This file is generated, DO NOT EDIT.
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/Methodical/flowgraph/dev10_bug679008/zeroInitStackSlot.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
* The JIT was removing a zero-init, but then emitting an untracked lifetime.
* Please run under GCSTRESS = 0x4
*/
using System;
using System.Runtime.CompilerServices;
internal struct SqlBinary
{
private byte[] _value;
}
internal class WarehouseResultDatabase : IDisposable
{
[MethodImpl(MethodImplOptions.NoInlining)]
public WarehouseResultDatabase()
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
void IDisposable.Dispose()
{
}
}
internal delegate bool WarehouseRowVersionQueryDelegate(WarehouseResultDatabase database, SqlBinary waterMark);
internal class Repro
{
private static int Main()
{
new Repro().ProcessResults(Query);
return 100;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void GetProcessingParameters(out SqlBinary binary)
{
binary = new SqlBinary();
}
private static bool Query(WarehouseResultDatabase database, SqlBinary waterMark)
{
return false;
}
private void ProcessResults(WarehouseRowVersionQueryDelegate query)
{
SqlBinary binary;
bool moreDataAvailable = true;
this.GetProcessingParameters(out binary);
SqlBinary waterMark = binary;
while (moreDataAvailable)
{
bool result = false;
using (WarehouseResultDatabase database = new WarehouseResultDatabase())
{
result = query(database, waterMark);
}
moreDataAvailable = result;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
* The JIT was removing a zero-init, but then emitting an untracked lifetime.
* Please run under GCSTRESS = 0x4
*/
using System;
using System.Runtime.CompilerServices;
internal struct SqlBinary
{
private byte[] _value;
}
internal class WarehouseResultDatabase : IDisposable
{
[MethodImpl(MethodImplOptions.NoInlining)]
public WarehouseResultDatabase()
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
void IDisposable.Dispose()
{
}
}
internal delegate bool WarehouseRowVersionQueryDelegate(WarehouseResultDatabase database, SqlBinary waterMark);
internal class Repro
{
private static int Main()
{
new Repro().ProcessResults(Query);
return 100;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void GetProcessingParameters(out SqlBinary binary)
{
binary = new SqlBinary();
}
private static bool Query(WarehouseResultDatabase database, SqlBinary waterMark)
{
return false;
}
private void ProcessResults(WarehouseRowVersionQueryDelegate query)
{
SqlBinary binary;
bool moreDataAvailable = true;
this.GetProcessingParameters(out binary);
SqlBinary waterMark = binary;
while (moreDataAvailable)
{
bool result = false;
using (WarehouseResultDatabase database = new WarehouseResultDatabase())
{
result = query(database, waterMark);
}
moreDataAvailable = result;
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/import_v13_b.xsd | <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="ns-b"
xmlns="ns-b">
<xsd:import namespace="ns-c" schemaLocation="import_v13_c.xsd"/>
<xsd:import namespace="ns-d" schemaLocation="import_v13_d.xsd"/>
<xsd:complexType name="ct-A">
<xsd:sequence minOccurs="1">
<xsd:element name="a1" type="xsd:boolean" />
<xsd:element name="a2" type="xsd:int" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="e1" type="ct-A" />
</xsd:schema>
| <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="ns-b"
xmlns="ns-b">
<xsd:import namespace="ns-c" schemaLocation="import_v13_c.xsd"/>
<xsd:import namespace="ns-d" schemaLocation="import_v13_d.xsd"/>
<xsd:complexType name="ct-A">
<xsd:sequence minOccurs="1">
<xsd:element name="a1" type="xsd:boolean" />
<xsd:element name="a2" type="xsd:int" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="e1" type="ct-A" />
</xsd:schema>
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/Regression/JitBlue/Runtime_57912/Runtime_57912.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;
[StructLayout(LayoutKind.Sequential)]
internal struct AA
{
public short tmp1;
public short q;
public ushort tmp2;
public int tmp3;
public AA(short qq)
{
tmp1 = 106;
tmp2 = 107;
tmp3 = 108;
q = qq;
}
// The test verifies that we accurately update the byref variable that is a field of struct.
public static short call_target_ref(ref short arg) { arg = 100; return arg; }
}
public class Runtime_57912
{
public static int Main()
{
return (int)test_0_17(100, new AA(100), new AA(0));
}
[MethodImpl(MethodImplOptions.NoInlining)]
static short test_0_17(int num, AA init, AA zero)
{
return AA.call_target_ref(ref init.q);
}
} | // 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;
[StructLayout(LayoutKind.Sequential)]
internal struct AA
{
public short tmp1;
public short q;
public ushort tmp2;
public int tmp3;
public AA(short qq)
{
tmp1 = 106;
tmp2 = 107;
tmp3 = 108;
q = qq;
}
// The test verifies that we accurately update the byref variable that is a field of struct.
public static short call_target_ref(ref short arg) { arg = 100; return arg; }
}
public class Runtime_57912
{
public static int Main()
{
return (int)test_0_17(100, new AA(100), new AA(0));
}
[MethodImpl(MethodImplOptions.NoInlining)]
static short test_0_17(int num, AA init, AA zero)
{
return AA.call_target_ref(ref init.q);
}
} | -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/jit64/valuetypes/nullable/castclass/castclass/castclass021.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(object o)
{
return Helper.Compare((EmptyStruct)(ValueType)o, Helper.Create(default(EmptyStruct)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((EmptyStruct?)(ValueType)o, Helper.Create(default(EmptyStruct)));
}
private static int Main()
{
EmptyStruct? s = Helper.Create(default(EmptyStruct));
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(object o)
{
return Helper.Compare((EmptyStruct)(ValueType)o, Helper.Create(default(EmptyStruct)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((EmptyStruct?)(ValueType)o, Helper.Create(default(EmptyStruct)));
}
private static int Main()
{
EmptyStruct? s = Helper.Create(default(EmptyStruct));
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/X86/Avx1/TestNotZAndNotC.Int32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestNotZAndNotCInt32()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
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 BooleanBinaryOpTest__TestNotZAndNotCInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (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<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 Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
fixed (Vector256<Int32>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
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<Int32> op1, Vector256<Int32> op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<Int32>(Vector256<Int32>, Vector256<Int32>): {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;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestNotZAndNotCInt32()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
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 BooleanBinaryOpTest__TestNotZAndNotCInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (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<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 Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCInt32 testClass)
{
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCInt32();
fixed (Vector256<Int32>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((Int32*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
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<Int32> op1, Vector256<Int32> op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<Int32>(Vector256<Int32>, Vector256<Int32>): {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,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/Loader/classloader/InterfaceFolding/Nested_I/TestCase4.il | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern mscorlib {}
.assembly extern xunit.core {}
.assembly TestCase4 {}
// =============== CLASS MEMBERS DECLARATION ===================
.class interface private abstract auto ansi J
{
.method public hidebysig newslot abstract virtual instance string Bar1() cil managed {}
.method public hidebysig newslot abstract virtual instance string Bar2() cil managed {}
}
.class private abstract auto ansi beforefieldinit A`1<U>
implements class A`1/I`1<!U>
{
.class interface nested family abstract auto ansi I`1<T>
{ .method public hidebysig newslot abstract virtual instance string Foo() cil managed {} }
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ret
}
}
.class private abstract auto ansi beforefieldinit B`2<V,W>
extends class A`1<!V>
implements class A`1/I`1<!W>, J
{
.method public hidebysig newslot virtual instance string Foo() cil managed
{
ldstr "B::Foo"
ret
}
.method public hidebysig newslot virtual instance string Bar1() cil managed
{
.maxstack 8
ldstr "B::Bar1"
ret
}
.method public hidebysig newslot virtual instance string Bar2() cil managed
{
.maxstack 8
ldstr "B::Bar2"
ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ret
}
}
.class private auto ansi beforefieldinit C extends class B`2<class C,class C>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ret
}
}
.class public auto ansi beforefieldinit Test_TestCase4 extends [mscorlib]System.Object
{
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
newobj instance void C::.ctor()
callvirt instance string class C::Foo()
ldstr "B::Foo"
call bool [mscorlib]System.String::op_Inequality(string, string)
brtrue FAILURE
newobj instance void C::.ctor()
callvirt instance string class C::Bar1()
ldstr "B::Bar1"
call bool [mscorlib]System.String::op_Inequality(string,string)
brtrue FAILURE
newobj instance void C::.ctor()
callvirt instance string class C::Bar2()
ldstr "B::Bar2"
call bool [mscorlib]System.String::op_Inequality(string,string)
brtrue FAILURE
PASS:
ldstr "Pass"
call void [mscorlib]System.Console::WriteLine(string)
ldc.i4.s 100
ret
FAILURE:
ldstr "Failed!"
call void [mscorlib]System.Console::WriteLine(string)
ldc.i4.m1
ret
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern mscorlib {}
.assembly extern xunit.core {}
.assembly TestCase4 {}
// =============== CLASS MEMBERS DECLARATION ===================
.class interface private abstract auto ansi J
{
.method public hidebysig newslot abstract virtual instance string Bar1() cil managed {}
.method public hidebysig newslot abstract virtual instance string Bar2() cil managed {}
}
.class private abstract auto ansi beforefieldinit A`1<U>
implements class A`1/I`1<!U>
{
.class interface nested family abstract auto ansi I`1<T>
{ .method public hidebysig newslot abstract virtual instance string Foo() cil managed {} }
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ret
}
}
.class private abstract auto ansi beforefieldinit B`2<V,W>
extends class A`1<!V>
implements class A`1/I`1<!W>, J
{
.method public hidebysig newslot virtual instance string Foo() cil managed
{
ldstr "B::Foo"
ret
}
.method public hidebysig newslot virtual instance string Bar1() cil managed
{
.maxstack 8
ldstr "B::Bar1"
ret
}
.method public hidebysig newslot virtual instance string Bar2() cil managed
{
.maxstack 8
ldstr "B::Bar2"
ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ret
}
}
.class private auto ansi beforefieldinit C extends class B`2<class C,class C>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ret
}
}
.class public auto ansi beforefieldinit Test_TestCase4 extends [mscorlib]System.Object
{
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
newobj instance void C::.ctor()
callvirt instance string class C::Foo()
ldstr "B::Foo"
call bool [mscorlib]System.String::op_Inequality(string, string)
brtrue FAILURE
newobj instance void C::.ctor()
callvirt instance string class C::Bar1()
ldstr "B::Bar1"
call bool [mscorlib]System.String::op_Inequality(string,string)
brtrue FAILURE
newobj instance void C::.ctor()
callvirt instance string class C::Bar2()
ldstr "B::Bar2"
call bool [mscorlib]System.String::op_Inequality(string,string)
brtrue FAILURE
PASS:
ldstr "Pass"
call void [mscorlib]System.Console::WriteLine(string)
ldc.i4.s 100
ret
FAILURE:
ldstr "Failed!"
call void [mscorlib]System.Console::WriteLine(string)
ldc.i4.m1
ret
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/System.Memory/tests/ParsersAndFormatters/Parser/TestData.Parser.DecimalsAndFloats.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.Linq;
using System.Globalization;
using System.Collections.Generic;
namespace System.Buffers.Text.Tests
{
internal static partial class TestData
{
public static IEnumerable<ParserTestData<decimal>> DecimalParserTestData
{
get
{
foreach (FormatterTestData<decimal> ftd in DecimalFormatterTestData)
{
// Not all FormatTestDatas for Decimal are actually roundtrippable.
if (ftd.FormatSymbol != default(char))
continue;
MutableDecimal d = ftd.Value.ToMutableDecimal();
if (d.High == 0 && d.Mid == 0 && d.Low == 0 && d.IsNegative)
continue; // -0 is not roundtrippable
foreach (ParserTestData<decimal> testData in new FormatterTestData<decimal>[] { ftd }.ToParserTheoryDataCollection())
{
yield return testData;
}
}
foreach (ParserTestData<decimal> testData in GenerateNumberBasedParserTestData<decimal>(DecimalFormats, decimal.TryParse))
{
yield return testData;
}
yield return new ParserTestData<decimal>("1e" + int.MaxValue, default, 'E', expectedSuccess: false);
yield return new ParserTestData<decimal>("0.01e" + int.MinValue, new MutableDecimal() { Scale = 28 }.ToDecimal(), 'E', expectedSuccess: true);
yield return new ParserTestData<decimal>("-0.01e" + int.MinValue, new MutableDecimal() { Scale = 28, IsNegative = true }.ToDecimal(), 'E', expectedSuccess: true);
}
}
public static IEnumerable<ParserTestData<double>> DoubleParserTestData
{
get
{
foreach (ParserTestData<double> testData in GenerateNumberBasedParserTestData<double>(FloatingPointFormats, double.TryParse))
{
yield return testData;
}
foreach (char formatSymbol in DecimalFormats.Select(f => f.Symbol))
{
yield return new ParserTestData<double>("Infinity", double.PositiveInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<double>("-Infinity", double.NegativeInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<double>("NaN", double.NaN, formatSymbol, expectedSuccess: true);
}
}
}
public static IEnumerable<ParserTestData<float>> SingleParserTestData
{
get
{
foreach (ParserTestData<float> testData in GenerateNumberBasedParserTestData<float>(FloatingPointFormats, float.TryParse))
{
yield return testData;
}
foreach (char formatSymbol in DecimalFormats.Select(f => f.Symbol))
{
yield return new ParserTestData<float>("Infinity", float.PositiveInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<float>("-Infinity", float.NegativeInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<float>("NaN", float.NaN, formatSymbol, expectedSuccess: true);
}
}
}
private static IEnumerable<ParserTestData<T>> GenerateNumberBasedParserTestData<T>(IEnumerable<SupportedFormat> formats, TryParseDelegate<T> tryParse)
{
foreach (char formatSymbol in formats.Select(f => f.Symbol))
{
foreach (ParserTestData<T> testData in GeneratedParserTestDataUsingParseExact<T>(formatSymbol, NumberTestData,
(string text, string format, IFormatProvider formatProvider, out T result) =>
{
NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign;
if (formatSymbol != 'F' && formatSymbol != 'f')
{
style |= NumberStyles.AllowExponent;
}
if ((formatSymbol == 'E' || formatSymbol == 'e') && text.IndexOf("E", StringComparison.InvariantCultureIgnoreCase) == -1)
{
result = default;
return false;
}
else
{
return tryParse(text, style, formatProvider, out result);
}
}))
{
yield return testData;
}
}
}
private delegate bool TryParseDelegate<T>(string text, NumberStyles style, IFormatProvider formatProvider, out T result);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
namespace System.Buffers.Text.Tests
{
internal static partial class TestData
{
public static IEnumerable<ParserTestData<decimal>> DecimalParserTestData
{
get
{
foreach (FormatterTestData<decimal> ftd in DecimalFormatterTestData)
{
// Not all FormatTestDatas for Decimal are actually roundtrippable.
if (ftd.FormatSymbol != default(char))
continue;
MutableDecimal d = ftd.Value.ToMutableDecimal();
if (d.High == 0 && d.Mid == 0 && d.Low == 0 && d.IsNegative)
continue; // -0 is not roundtrippable
foreach (ParserTestData<decimal> testData in new FormatterTestData<decimal>[] { ftd }.ToParserTheoryDataCollection())
{
yield return testData;
}
}
foreach (ParserTestData<decimal> testData in GenerateNumberBasedParserTestData<decimal>(DecimalFormats, decimal.TryParse))
{
yield return testData;
}
yield return new ParserTestData<decimal>("1e" + int.MaxValue, default, 'E', expectedSuccess: false);
yield return new ParserTestData<decimal>("0.01e" + int.MinValue, new MutableDecimal() { Scale = 28 }.ToDecimal(), 'E', expectedSuccess: true);
yield return new ParserTestData<decimal>("-0.01e" + int.MinValue, new MutableDecimal() { Scale = 28, IsNegative = true }.ToDecimal(), 'E', expectedSuccess: true);
}
}
public static IEnumerable<ParserTestData<double>> DoubleParserTestData
{
get
{
foreach (ParserTestData<double> testData in GenerateNumberBasedParserTestData<double>(FloatingPointFormats, double.TryParse))
{
yield return testData;
}
foreach (char formatSymbol in DecimalFormats.Select(f => f.Symbol))
{
yield return new ParserTestData<double>("Infinity", double.PositiveInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<double>("-Infinity", double.NegativeInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<double>("NaN", double.NaN, formatSymbol, expectedSuccess: true);
}
}
}
public static IEnumerable<ParserTestData<float>> SingleParserTestData
{
get
{
foreach (ParserTestData<float> testData in GenerateNumberBasedParserTestData<float>(FloatingPointFormats, float.TryParse))
{
yield return testData;
}
foreach (char formatSymbol in DecimalFormats.Select(f => f.Symbol))
{
yield return new ParserTestData<float>("Infinity", float.PositiveInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<float>("-Infinity", float.NegativeInfinity, formatSymbol, expectedSuccess: true);
yield return new ParserTestData<float>("NaN", float.NaN, formatSymbol, expectedSuccess: true);
}
}
}
private static IEnumerable<ParserTestData<T>> GenerateNumberBasedParserTestData<T>(IEnumerable<SupportedFormat> formats, TryParseDelegate<T> tryParse)
{
foreach (char formatSymbol in formats.Select(f => f.Symbol))
{
foreach (ParserTestData<T> testData in GeneratedParserTestDataUsingParseExact<T>(formatSymbol, NumberTestData,
(string text, string format, IFormatProvider formatProvider, out T result) =>
{
NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign;
if (formatSymbol != 'F' && formatSymbol != 'f')
{
style |= NumberStyles.AllowExponent;
}
if ((formatSymbol == 'E' || formatSymbol == 'e') && text.IndexOf("E", StringComparison.InvariantCultureIgnoreCase) == -1)
{
result = default;
return false;
}
else
{
return tryParse(text, style, formatProvider, out result);
}
}))
{
yield return testData;
}
}
}
private delegate bool TryParseDelegate<T>(string text, NumberStyles style, IFormatProvider formatProvider, out T result);
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/Common/tests/System/Net/Prerequisites/Servers/CoreFxNetCloudService/WebServer/Deflate.ashx | <%@ WebHandler Language="C#" CodeBehind="Deflate.ashx.cs" Class="WebServer.Deflate" %>
| <%@ WebHandler Language="C#" CodeBehind="Deflate.ashx.cs" Class="WebServer.Deflate" %>
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/X86/Avx1/InsertVector128.Byte.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.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertVector128Byte1()
{
var test = new ImmBinaryOpTest__InsertVector128Byte1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__InsertVector128Byte1
{
private struct TestStruct
{
public Vector256<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__InsertVector128Byte1 testClass)
{
var result = Avx.InsertVector128(_fld1, _fld2, 1);
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<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable;
static ImmBinaryOpTest__InsertVector128Byte1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public ImmBinaryOpTest__InsertVector128Byte1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.InsertVector128(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.InsertVector128(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.InsertVector128(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.InsertVector128(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__InsertVector128Byte1();
var result = Avx.InsertVector128(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.InsertVector128(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.InsertVector128(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != left[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 16 ? left[i] : right[i-16]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.InsertVector128)}<Byte>(Vector256<Byte>.1, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertVector128Byte1()
{
var test = new ImmBinaryOpTest__InsertVector128Byte1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__InsertVector128Byte1
{
private struct TestStruct
{
public Vector256<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__InsertVector128Byte1 testClass)
{
var result = Avx.InsertVector128(_fld1, _fld2, 1);
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<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable;
static ImmBinaryOpTest__InsertVector128Byte1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public ImmBinaryOpTest__InsertVector128Byte1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.InsertVector128(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.InsertVector128(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.InsertVector128(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.InsertVector128(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Avx.InsertVector128(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__InsertVector128Byte1();
var result = Avx.InsertVector128(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.InsertVector128(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.InsertVector128(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != left[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 16 ? left[i] : right[i-16]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.InsertVector128)}<Byte>(Vector256<Byte>.1, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/coreclr/pal/src/safecrt/output.inl | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/***
*output.c - printf style output to a FILE
*
*
*Purpose:
* This file contains the code that does all the work for the
* printf family of functions. It should not be called directly, only
* by the *printf functions. We don't make any assumtions about the
* sizes of ints, longs, shorts, or long doubles, but if types do overlap,
* we also try to be efficient. We do assume that pointers are the same
* size as either ints or longs.
* If CPRFLAG is defined, defines _cprintf instead.
* **** DOESN'T CURRENTLY DO MTHREAD LOCKING ****
*
*Note:
* this file is included in safecrt.lib build directly, plese refer
* to safecrt_[w]output_s.c
*
*******************************************************************************/
//typedef __int64_t __int64;
#define FORMAT_VALIDATIONS
typedef double _CRT_DOUBLE;
//typedef int* intptr_t;
/*
Buffer size required to be passed to _gcvt, fcvt and other fp conversion routines
*/
#define _CVTBUFSIZE (309+40) /* # of digits in max. dp value + slop */
/* temporary work-around for compiler without 64-bit support */
#ifndef _INTEGRAL_MAX_BITS
#define _INTEGRAL_MAX_BITS 64
#endif /* _INTEGRAL_MAX_BITS */
//#include <mtdll.h>
//#include <cruntime.h>
//#include <limits.h>
//#include <string.h>
//#include <stddef.h>
//#include <crtdefs.h>
//#include <stdio.h>
//#include <stdarg.h>
//#include <cvt.h>
//#include <conio.h>
//#include <internal.h>
//#include <fltintrn.h>
//#include <stdlib.h>
//#include <ctype.h>
//#include <dbgint.h>
//#include <setlocal.h>
#define _MBTOWC(x,y,z) _minimal_chartowchar( x, y )
#ifndef _WCTOMB_S
#define _WCTOMB_S wctomb_s
#endif /* _WCTOMB_S */
#undef _malloc_crt
#define _malloc_crt malloc
#undef _free_crt
#define _free_crt free
#ifndef _CFLTCVT
#define _CFLTCVT _cfltcvt
#endif /* _CFLTCVT */
#ifndef _CLDCVT
#define _CLDCVT _cldcvt
#endif /* _CLDCVT */
/* this macro defines a function which is private and as fast as possible: */
/* for example, in C 6.0, it might be static _fastcall <type> near. */
#define LOCAL(x) static x __cdecl
/* int/long/short/pointer sizes */
/* the following should be set depending on the sizes of various types */
#if __LP64__
#define LONG_IS_INT 0
CASSERT(sizeof(long) > sizeof(int));
#else
#define LONG_IS_INT 1 /* 1 means long is same size as int */
CASSERT(sizeof(long) == sizeof(int));
#endif
#define SHORT_IS_INT 0 /* 1 means short is same size as int */
#define LONGLONG_IS_INT64 1 /* 1 means long long is same as int64 */
#if defined (HOST_64BIT)
#define PTR_IS_INT 0 /* 1 means ptr is same size as int */
CASSERT(sizeof(void *) != sizeof(int));
#if __LP64__
#define PTR_IS_LONG 1 /* 1 means ptr is same size as long */
CASSERT(sizeof(void *) == sizeof(long));
#else
#define PTR_IS_LONG 0 /* 1 means ptr is same size as long */
CASSERT(sizeof(void *) != sizeof(long));
#endif
#define PTR_IS_INT64 1 /* 1 means ptr is same size as int64 */
CASSERT(sizeof(void *) == sizeof(int64_t));
#else /* defined (HOST_64BIT) */
#define PTR_IS_INT 1 /* 1 means ptr is same size as int */
CASSERT(sizeof(void *) == sizeof(int));
#define PTR_IS_LONG 1 /* 1 means ptr is same size as long */
CASSERT(sizeof(void *) == sizeof(long));
#define PTR_IS_INT64 0 /* 1 means ptr is same size as int64 */
CASSERT(sizeof(void *) != sizeof(int64_t));
#endif /* defined (HOST_64BIT) */
/* CONSTANTS */
/* size of conversion buffer (ANSI-specified minimum is 509) */
#define BUFFERSIZE 512
#define MAXPRECISION BUFFERSIZE
#if BUFFERSIZE < _CVTBUFSIZE + 6
/*
* Buffer needs to be big enough for default minimum precision
* when converting floating point needs bigger buffer, and malloc
* fails
*/
#error Conversion buffer too small for max double.
#endif /* BUFFERSIZE < _CVTBUFSIZE + 6 */
/* flag definitions */
#define FL_SIGN 0x00001 /* put plus or minus in front */
#define FL_SIGNSP 0x00002 /* put space or minus in front */
#define FL_LEFT 0x00004 /* left justify */
#define FL_LEADZERO 0x00008 /* pad with leading zeros */
#define FL_LONG 0x00010 /* long value given */
#define FL_SHORT 0x00020 /* short value given */
#define FL_SIGNED 0x00040 /* signed data given */
#define FL_ALTERNATE 0x00080 /* alternate form requested */
#define FL_NEGATIVE 0x00100 /* value is negative */
#define FL_FORCEOCTAL 0x00200 /* force leading '0' for octals */
#define FL_LONGDOUBLE 0x00400 /* long double value given */
#define FL_WIDECHAR 0x00800 /* wide characters */
#define FL_LONGLONG 0x01000 /* long long value given */
#define FL_I64 0x08000 /* __int64 value given */
/* state definitions */
enum STATE {
ST_NORMAL, /* normal state; outputting literal chars */
ST_PERCENT, /* just read '%' */
ST_FLAG, /* just read flag character */
ST_WIDTH, /* just read width specifier */
ST_DOT, /* just read '.' */
ST_PRECIS, /* just read precision specifier */
ST_SIZE, /* just read size specifier */
ST_TYPE /* just read type specifier */
#ifdef FORMAT_VALIDATIONS
,ST_INVALID /* Invalid format */
#endif /* FORMAT_VALIDATIONS */
};
#ifdef FORMAT_VALIDATIONS
#define NUMSTATES (ST_INVALID + 1)
#else /* FORMAT_VALIDATIONS */
#define NUMSTATES (ST_TYPE + 1)
#endif /* FORMAT_VALIDATIONS */
/* character type values */
enum CHARTYPE {
CH_OTHER, /* character with no special meaning */
CH_PERCENT, /* '%' */
CH_DOT, /* '.' */
CH_STAR, /* '*' */
CH_ZERO, /* '0' */
CH_DIGIT, /* '1'..'9' */
CH_FLAG, /* ' ', '+', '-', '#' */
CH_SIZE, /* 'h', 'l', 'L', 'N', 'F', 'w' */
CH_TYPE /* type specifying character */
};
/* static data (read only, since we are re-entrant) */
//#if defined (_UNICODE) || defined (CPRFLAG) || defined (FORMAT_VALIDATIONS)
//extern const char __nullstring[]; /* string to print on null ptr */
//extern const char16_t __wnullstring[]; /* string to print on null ptr */
//#else /* defined (_UNICODE) || defined (CPRFLAG) || defined (FORMAT_VALIDATIONS) */
static const char __nullstring[] = "(null)"; /* string to print on null ptr */
static const char16_t __wnullstring[] = {'(', 'n', 'u', 'l', 'l', ')', '\0'};/* string to print on null ptr */
//#endif /* defined (_UNICODE) || defined (CPRFLAG) || defined (FORMAT_VALIDATIONS) */
/* The state table. This table is actually two tables combined into one. */
/* The lower nybble of each byte gives the character class of any */
/* character; while the uper nybble of the byte gives the next state */
/* to enter. See the macros below the table for details. */
/* */
/* The table is generated by maketabc.c -- use this program to make */
/* changes. */
#ifndef FORMAT_VALIDATIONS
//#if defined (_UNICODE) || defined (CPRFLAG)
//extern const char __lookuptable[];
//#else /* defined (_UNICODE) || defined (CPRFLAG) */
extern const char __lookuptable[] = {
/* ' ' */ 0x06,
/* '!' */ 0x00,
/* '"' */ 0x00,
/* '#' */ 0x06,
/* '$' */ 0x00,
/* '%' */ 0x01,
/* '&' */ 0x00,
/* ''' */ 0x00,
/* '(' */ 0x10,
/* ')' */ 0x00,
/* '*' */ 0x03,
/* '+' */ 0x06,
/* ',' */ 0x00,
/* '-' */ 0x06,
/* '.' */ 0x02,
/* '/' */ 0x10,
/* '0' */ 0x04,
/* '1' */ 0x45,
/* '2' */ 0x45,
/* '3' */ 0x45,
/* '4' */ 0x05,
/* '5' */ 0x05,
/* '6' */ 0x05,
/* '7' */ 0x05,
/* '8' */ 0x05,
/* '9' */ 0x35,
/* ':' */ 0x30,
/* ';' */ 0x00,
/* '<' */ 0x50,
/* '=' */ 0x00,
/* '>' */ 0x00,
/* '?' */ 0x00,
/* '@' */ 0x00,
/* 'A' */ 0x20, // Disable %A format
/* 'B' */ 0x20,
/* 'C' */ 0x38,
/* 'D' */ 0x50,
/* 'E' */ 0x58,
/* 'F' */ 0x07,
/* 'G' */ 0x08,
/* 'H' */ 0x00,
/* 'I' */ 0x37,
/* 'J' */ 0x30,
/* 'K' */ 0x30,
/* 'L' */ 0x57,
/* 'M' */ 0x50,
/* 'N' */ 0x07,
/* 'O' */ 0x00,
/* 'P' */ 0x00,
/* 'Q' */ 0x20,
/* 'R' */ 0x20,
/* 'S' */ 0x08,
/* 'T' */ 0x00,
/* 'U' */ 0x00,
/* 'V' */ 0x00,
/* 'W' */ 0x00,
/* 'X' */ 0x08,
/* 'Y' */ 0x60,
/* 'Z' */ 0x68,
/* '[' */ 0x60,
/* '\' */ 0x60,
/* ']' */ 0x60,
/* '^' */ 0x60,
/* '_' */ 0x00,
/* '`' */ 0x00,
/* 'a' */ 0x70, // Disable %a format
/* 'b' */ 0x70,
/* 'c' */ 0x78,
/* 'd' */ 0x78,
/* 'e' */ 0x78,
/* 'f' */ 0x78,
/* 'g' */ 0x08,
/* 'h' */ 0x07,
/* 'i' */ 0x08,
/* 'j' */ 0x00,
/* 'k' */ 0x00,
/* 'l' */ 0x07,
/* 'm' */ 0x00,
/* 'n' */ 0x00, // Disable %n format
/* 'o' */ 0x08,
/* 'p' */ 0x08,
/* 'q' */ 0x00,
/* 'r' */ 0x00,
/* 's' */ 0x08,
/* 't' */ 0x00,
/* 'u' */ 0x08,
/* 'v' */ 0x00,
/* 'w' */ 0x07,
/* 'x' */ 0x08
};
//#endif /* defined (_UNICODE) || defined (CPRFLAG) */
#else /* FORMAT_VALIDATIONS */
//#if defined (_UNICODE) || defined (CPRFLAG)
//extern const unsigned char __lookuptable_s[];
//#else /* defined (_UNICODE) || defined (CPRFLAG) */
static const unsigned char __lookuptable_s[] = {
/* ' ' */ 0x06,
/* '!' */ 0x80,
/* '"' */ 0x80,
/* '#' */ 0x86,
/* '$' */ 0x80,
/* '%' */ 0x81,
/* '&' */ 0x80,
/* ''' */ 0x00,
/* '(' */ 0x00,
/* ')' */ 0x10,
/* '*' */ 0x03,
/* '+' */ 0x86,
/* ',' */ 0x80,
/* '-' */ 0x86,
/* '.' */ 0x82,
/* '/' */ 0x80,
/* '0' */ 0x14,
/* '1' */ 0x05,
/* '2' */ 0x05,
/* '3' */ 0x45,
/* '4' */ 0x45,
/* '5' */ 0x45,
/* '6' */ 0x85,
/* '7' */ 0x85,
/* '8' */ 0x85,
/* '9' */ 0x05,
/* ':' */ 0x00,
/* ';' */ 0x00,
/* '<' */ 0x30,
/* '=' */ 0x30,
/* '>' */ 0x80,
/* '?' */ 0x50,
/* '@' */ 0x80,
/* 'A' */ 0x80, // Disable %A format
/* 'B' */ 0x00,
/* 'C' */ 0x08,
/* 'D' */ 0x00,
/* 'E' */ 0x28,
/* 'F' */ 0x27,
/* 'G' */ 0x38,
/* 'H' */ 0x50,
/* 'I' */ 0x57,
/* 'J' */ 0x80,
/* 'K' */ 0x00,
/* 'L' */ 0x07,
/* 'M' */ 0x00,
/* 'N' */ 0x37,
/* 'O' */ 0x30,
/* 'P' */ 0x30,
/* 'Q' */ 0x50,
/* 'R' */ 0x50,
/* 'S' */ 0x88,
/* 'T' */ 0x00,
/* 'U' */ 0x00,
/* 'V' */ 0x00,
/* 'W' */ 0x20,
/* 'X' */ 0x28,
/* 'Y' */ 0x80,
/* 'Z' */ 0x88,
/* '[' */ 0x80,
/* '\' */ 0x80,
/* ']' */ 0x00,
/* '^' */ 0x00,
/* '_' */ 0x00,
/* '`' */ 0x60,
/* 'a' */ 0x60, // Disable %a format
/* 'b' */ 0x60,
/* 'c' */ 0x68,
/* 'd' */ 0x68,
/* 'e' */ 0x68,
/* 'f' */ 0x08,
/* 'g' */ 0x08,
/* 'h' */ 0x07,
/* 'i' */ 0x78,
/* 'j' */ 0x70,
/* 'k' */ 0x70,
/* 'l' */ 0x77,
/* 'm' */ 0x70,
/* 'n' */ 0x70,
/* 'o' */ 0x08,
/* 'p' */ 0x08,
/* 'q' */ 0x00,
/* 'r' */ 0x00,
/* 's' */ 0x08,
/* 't' */ 0x00,
/* 'u' */ 0x08,
/* 'v' */ 0x00,
/* 'w' */ 0x07,
/* 'x' */ 0x08
};
//#endif /* defined (_UNICODE) || defined (CPRFLAG) */
#endif /* FORMAT_VALIDATIONS */
#define FIND_CHAR_CLASS(lookuptbl, c) \
((c) < _T(' ') || (c) > _T('x') ? \
CH_OTHER \
: \
(enum CHARTYPE)(lookuptbl[(c)-_T(' ')] & 0xF))
#define FIND_NEXT_STATE(lookuptbl, class, state) \
(enum STATE)(lookuptbl[(class) * NUMSTATES + (state)] >> 4)
/*
* Note: CPRFLAG and _UNICODE cases are currently mutually exclusive.
*/
/* prototypes */
#ifdef CPRFLAG
#define WRITE_CHAR(ch, pnw) write_char(ch, pnw)
#define WRITE_MULTI_CHAR(ch, num, pnw) write_multi_char(ch, num, pnw)
#define WRITE_STRING(s, len, pnw) write_string(s, len, pnw)
LOCAL(void) write_char(_TCHAR ch, int *pnumwritten);
LOCAL(void) write_multi_char(_TCHAR ch, int num, int *pnumwritten);
LOCAL(void) write_string(const _TCHAR *string, int len, int *numwritten);
#else /* CPRFLAG */
#define WRITE_CHAR(ch, pnw) write_char(ch, stream, pnw)
#define WRITE_MULTI_CHAR(ch, num, pnw) write_multi_char(ch, num, stream, pnw)
#define WRITE_STRING(s, len, pnw) write_string(s, len, stream, pnw)
LOCAL(void) write_char(_TCHAR ch, miniFILE *f, int *pnumwritten);
LOCAL(void) write_multi_char(_TCHAR ch, int num, miniFILE *f, int *pnumwritten);
LOCAL(void) write_string(const _TCHAR *string, int len, miniFILE *f, int *numwritten);
#endif /* CPRFLAG */
#define get_int_arg(list) va_arg(*list, int)
#define get_long_arg(list) va_arg(*list, long)
#define get_long_long_arg(list) va_arg(*list, long long)
#define get_int64_arg(list) va_arg(*list, __int64)
#define get_crtdouble_arg(list) va_arg(*list, _CRT_DOUBLE)
#define get_ptr_arg(list) va_arg(*list, void *)
#ifdef CPRFLAG
LOCAL(int) output(const _TCHAR *, _locale_t , va_list);
_CRTIMP int __cdecl _vtcprintf_l (const _TCHAR *, _locale_t, va_list);
_CRTIMP int __cdecl _vtcprintf_s_l (const _TCHAR *, _locale_t, va_list);
_CRTIMP int __cdecl _vtcprintf_p_l (const _TCHAR *, _locale_t, va_list);
/***
*int _cprintf(format, arglist) - write formatted output directly to console
*
*Purpose:
* Writes formatted data like printf, but uses console I/O functions.
*
*Entry:
* char *format - format string to determine data formats
* arglist - list of POINTERS to where to put data
*
*Exit:
* returns number of characters written
*
*Exceptions:
*
*******************************************************************************/
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _tcprintf_l (
const _TCHAR * format,
_locale_t plocinfo,
...
)
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _tcprintf_s_l (
const _TCHAR * format,
_locale_t plocinfo,
...
)
#endif /* FORMAT_VALIDATIONS */
{
int ret;
va_list arglist;
va_start(arglist, plocinfo);
#ifndef FORMAT_VALIDATIONS
ret = _vtcprintf_l(format, plocinfo, arglist);
#else /* FORMAT_VALIDATIONS */
ret = _vtcprintf_s_l(format, plocinfo, arglist);
#endif /* FORMAT_VALIDATIONS */
va_end(arglist);
return ret;
}
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _tcprintf (
const _TCHAR * format,
...
)
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _tcprintf_s (
const _TCHAR * format,
...
)
#endif /* FORMAT_VALIDATIONS */
{
int ret;
va_list arglist;
va_start(arglist, format);
#ifndef FORMAT_VALIDATIONS
ret = _vtcprintf_l(format, NULL, arglist);
#else /* FORMAT_VALIDATIONS */
ret = _vtcprintf_s_l(format, NULL, arglist);
#endif /* FORMAT_VALIDATIONS */
va_end(arglist);
return ret;
}
#endif /* CPRFLAG */
/***
*int _output(stream, format, argptr), static int output(format, argptr)
*
*Purpose:
* Output performs printf style output onto a stream. It is called by
* printf/fprintf/sprintf/vprintf/vfprintf/vsprintf to so the dirty
* work. In multi-thread situations, _output assumes that the given
* stream is already locked.
*
* Algorithm:
* The format string is parsed by using a finite state automaton
* based on the current state and the current character read from
* the format string. Thus, looping is on a per-character basis,
* not a per conversion specifier basis. Once the format specififying
* character is read, output is performed.
*
*Entry:
* FILE *stream - stream for output
* char *format - printf style format string
* va_list argptr - pointer to list of subsidiary arguments
*
*Exit:
* Returns the number of characters written, or -1 if an output error
* occurs.
*ifdef _UNICODE
* The wide-character flavour returns the number of wide-characters written.
*endif
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _vtcprintf (
const _TCHAR *format,
va_list argptr
)
{
return _vtcprintf_l(format, NULL, argptr);
}
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _vtcprintf_s (
const _TCHAR *format,
va_list argptr
)
{
return _vtcprintf_s_l(format, NULL, argptr);
}
#endif /* FORMAT_VALIDATIONS */
#endif /* CPRFLAG */
#ifdef CPRFLAG
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _vtcprintf_l (
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _vtcprintf_s_l (
#endif /* FORMAT_VALIDATIONS */
#else /* CPRFLAG */
#ifdef _UNICODE
#ifndef FORMAT_VALIDATIONS
int __cdecl _woutput (
miniFILE *stream,
#else /* FORMAT_VALIDATIONS */
int __cdecl _woutput_s (
miniFILE *stream,
#endif /* FORMAT_VALIDATIONS */
#else /* _UNICODE */
#ifndef FORMAT_VALIDATIONS
int __cdecl _output (
miniFILE *stream,
#else /* FORMAT_VALIDATIONS */
int __cdecl _output_s (
miniFILE *stream,
#endif /* FORMAT_VALIDATIONS */
#endif /* _UNICODE */
#endif /* CPRFLAG */
const _TCHAR *format,
va_list argptr
)
{
int hexadd=0; /* offset to add to number to get 'a'..'f' */
TCHAR ch; /* character just read */
int flags=0; /* flag word -- see #defines above for flag values */
enum STATE state; /* current state */
enum CHARTYPE chclass; /* class of current character */
int radix; /* current conversion radix */
int charsout; /* characters currently written so far, -1 = IO error */
int fldwidth = 0; /* selected field width -- 0 means default */
int precision = 0; /* selected precision -- -1 means default */
TCHAR prefix[2]; /* numeric prefix -- up to two characters */
int prefixlen=0; /* length of prefix -- 0 means no prefix */
int capexp = 0; /* non-zero = 'E' exponent signifient, zero = 'e' */
int no_output=0; /* non-zero = prodcue no output for this specifier */
union {
const char *sz; /* pointer text to be printed, not zero terminated */
const char16_t *wz;
} text;
int textlen; /* length of the text in bytes/wchars to be printed.
textlen is in multibyte or wide chars if _UNICODE */
union {
char sz[BUFFERSIZE];
#ifdef _UNICODE
char16_t wz[BUFFERSIZE];
#endif /* _UNICODE */
} buffer;
char16_t wchar; /* temp char16_t */
int buffersize; /* size of text.sz (used only for the call to _cfltcvt) */
int bufferiswide=0; /* non-zero = buffer contains wide chars already */
#ifndef CPRFLAG
_VALIDATE_RETURN( (stream != NULL), EINVAL, -1);
#endif /* CPRFLAG */
_VALIDATE_RETURN( (format != NULL), EINVAL, -1);
charsout = 0; /* no characters written yet */
textlen = 0; /* no text yet */
state = ST_NORMAL; /* starting state */
buffersize = 0;
/* main loop -- loop while format character exist and no I/O errors */
while ((ch = *format++) != _T('\0') && charsout >= 0) {
#ifndef FORMAT_VALIDATIONS
chclass = FIND_CHAR_CLASS(__lookuptable, ch); /* find character class */
state = FIND_NEXT_STATE(__lookuptable, chclass, state); /* find next state */
#else /* FORMAT_VALIDATIONS */
chclass = FIND_CHAR_CLASS(__lookuptable_s, ch); /* find character class */
state = FIND_NEXT_STATE(__lookuptable_s, chclass, state); /* find next state */
_VALIDATE_RETURN((state != ST_INVALID), EINVAL, -1);
#endif /* FORMAT_VALIDATIONS */
/* execute code for each state */
switch (state) {
case ST_NORMAL:
NORMAL_STATE:
/* normal state -- just write character */
#ifdef _UNICODE
bufferiswide = 1;
#else /* _UNICODE */
bufferiswide = 0;
#endif /* _UNICODE */
WRITE_CHAR(ch, &charsout);
break;
case ST_PERCENT:
/* set default value of conversion parameters */
prefixlen = fldwidth = no_output = capexp = 0;
flags = 0;
precision = -1;
bufferiswide = 0; /* default */
break;
case ST_FLAG:
/* set flag based on which flag character */
switch (ch) {
case _T('-'):
flags |= FL_LEFT; /* '-' => left justify */
break;
case _T('+'):
flags |= FL_SIGN; /* '+' => force sign indicator */
break;
case _T(' '):
flags |= FL_SIGNSP; /* ' ' => force sign or space */
break;
case _T('#'):
flags |= FL_ALTERNATE; /* '#' => alternate form */
break;
case _T('0'):
flags |= FL_LEADZERO; /* '0' => pad with leading zeros */
break;
}
break;
case ST_WIDTH:
/* update width value */
if (ch == _T('*')) {
/* get width from arg list */
fldwidth = get_int_arg(&argptr);
if (fldwidth < 0) {
/* ANSI says neg fld width means '-' flag and pos width */
flags |= FL_LEFT;
fldwidth = -fldwidth;
}
}
else {
/* add digit to current field width */
fldwidth = fldwidth * 10 + (ch - _T('0'));
}
break;
case ST_DOT:
/* zero the precision, since dot with no number means 0
not default, according to ANSI */
precision = 0;
break;
case ST_PRECIS:
/* update precison value */
if (ch == _T('*')) {
/* get precision from arg list */
precision = get_int_arg(&argptr);
if (precision < 0)
precision = -1; /* neg precision means default */
}
else {
/* add digit to current precision */
precision = precision * 10 + (ch - _T('0'));
}
break;
case ST_SIZE:
/* just read a size specifier, set the flags based on it */
switch (ch) {
case _T('l'):
/*
* In order to handle the ll case, we depart from the
* simple deterministic state machine.
*/
if (*format == _T('l'))
{
++format;
flags |= FL_LONGLONG; /* 'll' => long long */
}
else
{
flags |= FL_LONG; /* 'l' => long int or char16_t */
}
break;
case _T('L'):
if (*format == _T('p'))
{
flags |= FL_LONG;
}
break;
case _T('I'):
/*
* In order to handle the I, I32, and I64 size modifiers, we
* depart from the simple deterministic state machine. The
* code below scans for characters following the 'I',
* and defaults to 64 bit on WIN64 and 32 bit on WIN32
*/
#if PTR_IS_INT64
flags |= FL_I64; /* 'I' => __int64 on WIN64 systems */
#endif /* PTR_IS_INT64 */
if ( (*format == _T('6')) && (*(format + 1) == _T('4')) )
{
format += 2;
flags |= FL_I64; /* I64 => __int64 */
}
else if ( (*format == _T('3')) && (*(format + 1) == _T('2')) )
{
format += 2;
flags &= ~FL_I64; /* I32 => __int32 */
}
else if ( (*format == _T('d')) ||
(*format == _T('i')) ||
(*format == _T('o')) ||
(*format == _T('u')) ||
(*format == _T('x')) ||
(*format == _T('X')) )
{
/*
* Nothing further needed. %Id (et al) is
* handled just like %d, except that it defaults to 64 bits
* on WIN64. Fall through to the next iteration.
*/
}
else {
state = ST_NORMAL;
goto NORMAL_STATE;
}
break;
case _T('h'):
flags |= FL_SHORT; /* 'h' => short int or char */
break;
case _T('w'):
flags |= FL_WIDECHAR; /* 'w' => wide character */
break;
}
break;
case ST_TYPE:
/* we have finally read the actual type character, so we */
/* now format and "print" the output. We use a big switch */
/* statement that sets 'text' to point to the text that should */
/* be printed, and 'textlen' to the length of this text. */
/* Common code later on takes care of justifying it and */
/* other miscellaneous chores. Note that cases share code, */
/* in particular, all integer formatting is done in one place. */
/* Look at those funky goto statements! */
switch (ch) {
case _T('C'): /* ISO wide character */
if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
#ifdef _UNICODE
flags |= FL_SHORT;
#else /* _UNICODE */
flags |= FL_WIDECHAR; /* ISO std. */
#endif /* _UNICODE */
/* fall into 'c' case */
FALLTHROUGH;
case _T('c'): {
/* print a single character specified by int argument */
#ifdef _UNICODE
bufferiswide = 1;
wchar = (char16_t) get_int_arg(&argptr);
if (flags & FL_SHORT) {
/* format multibyte character */
/* this is an extension of ANSI */
char tempchar[2];
{
tempchar[0] = (char)(wchar & 0x00ff);
tempchar[1] = '\0';
}
if (_MBTOWC(buffer.wz,tempchar, MB_CUR_MAX) < 0)
{
/* ignore if conversion was unsuccessful */
no_output = 1;
}
} else {
buffer.wz[0] = wchar;
}
text.wz = buffer.wz;
textlen = 1; /* print just a single character */
#else /* _UNICODE */
if (flags & (FL_LONG|FL_WIDECHAR)) {
wchar = (char16_t) get_int_arg(&argptr);
textlen = snprintf(buffer.sz, BUFFERSIZE, "%lc", wchar);
if (textlen == 0)
{
no_output = 1;
}
} else {
/* format multibyte character */
/* this is an extension of ANSI */
unsigned short temp;
wchar = (char16_t)get_int_arg(&argptr);
temp = (unsigned short)wchar;
{
buffer.sz[0] = (char) temp;
textlen = 1;
}
}
text.sz = buffer.sz;
#endif /* _UNICODE */
}
break;
case _T('Z'): {
/* print a Counted String */
struct _count_string {
short Length;
short MaximumLength;
char *Buffer;
} *pstr;
pstr = (struct _count_string *)get_ptr_arg(&argptr);
if (pstr == NULL || pstr->Buffer == NULL) {
/* null ptr passed, use special string */
text.sz = __nullstring;
textlen = (int)strlen(text.sz);
} else {
if (flags & FL_WIDECHAR) {
text.wz = (char16_t *)pstr->Buffer;
textlen = pstr->Length / (int)sizeof(char16_t);
bufferiswide = 1;
} else {
bufferiswide = 0;
text.sz = pstr->Buffer;
textlen = pstr->Length;
}
}
}
break;
case _T('S'): /* ISO wide character string */
#ifndef _UNICODE
if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
flags |= FL_WIDECHAR;
#else /* _UNICODE */
if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
flags |= FL_SHORT;
#endif /* _UNICODE */
FALLTHROUGH;
case _T('s'): {
/* print a string -- */
/* ANSI rules on how much of string to print: */
/* all if precision is default, */
/* min(precision, length) if precision given. */
/* prints '(null)' if a null string is passed */
int i;
const char *p; /* temps */
const char16_t *pwch;
/* At this point it is tempting to use strlen(), but */
/* if a precision is specified, we're not allowed to */
/* scan past there, because there might be no null */
/* at all. Thus, we must do our own scan. */
i = (precision == -1) ? INT_MAX : precision;
text.sz = (char *)get_ptr_arg(&argptr);
/* scan for null upto i characters */
#ifdef _UNICODE
if (flags & FL_SHORT) {
if (text.sz == NULL) /* NULL passed, use special string */
text.sz = __nullstring;
p = text.sz;
for (textlen=0; textlen<i && *p; textlen++) {
++p;
}
/* textlen now contains length in multibyte chars */
} else {
if (text.wz == NULL) /* NULL passed, use special string */
text.wz = __wnullstring;
bufferiswide = 1;
pwch = text.wz;
while (i-- && *pwch)
++pwch;
textlen = (int)(pwch - text.wz); /* in char16_ts */
/* textlen now contains length in wide chars */
}
#else /* _UNICODE */
if (flags & (FL_LONG|FL_WIDECHAR)) {
if (text.wz == NULL) /* NULL passed, use special string */
text.wz = __wnullstring;
bufferiswide = 1;
pwch = text.wz;
while ( i-- && *pwch )
++pwch;
textlen = (int)(pwch - text.wz);
/* textlen now contains length in wide chars */
} else {
if (text.sz == NULL) /* NULL passed, use special string */
text.sz = __nullstring;
p = text.sz;
while (i-- && *p)
++p;
textlen = (int)(p - text.sz); /* length of the string */
}
#endif /* _UNICODE */
}
break;
case _T('n'): {
/* write count of characters seen so far into */
/* short/int/long thru ptr read from args */
void *p; /* temp */
p = get_ptr_arg(&argptr);
/* %n is disabled */
_VALIDATE_RETURN(("'n' format specifier disabled" && 0), EINVAL, -1);
break;
/* store chars out into short/long/int depending on flags */
#if !LONG_IS_INT
if (flags & FL_LONG)
*(long *)p = charsout;
else
#endif /* !LONG_IS_INT */
#if !SHORT_IS_INT
if (flags & FL_SHORT)
*(short *)p = (short) charsout;
else
#endif /* !SHORT_IS_INT */
*(int *)p = charsout;
no_output = 1; /* force no output */
}
break;
case _T('E'):
case _T('G'):
case _T('A'):
capexp = 1; /* capitalize exponent */
ch += _T('a') - _T('A'); /* convert format char to lower */
FALLTHROUGH;
case _T('e'):
case _T('f'):
case _T('g'):
case _T('a'): {
/* floating point conversion -- we call cfltcvt routines */
/* to do the work for us. */
flags |= FL_SIGNED; /* floating point is signed conversion */
text.sz = buffer.sz; /* put result in buffer */
buffersize = BUFFERSIZE;
/* compute the precision value */
if (precision < 0)
precision = 6; /* default precision: 6 */
else if (precision == 0 && ch == _T('g'))
precision = 1; /* ANSI specified */
else if (precision > MAXPRECISION)
precision = MAXPRECISION;
if (precision > BUFFERSIZE - _CVTBUFSIZE) {
/* cap precision further */
precision = BUFFERSIZE - _CVTBUFSIZE;
}
/* for safecrt, we pass along the FL_ALTERNATE flag to _safecrt_cfltcvt */
if (flags & FL_ALTERNATE)
{
capexp |= FL_ALTERNATE;
}
_CRT_DOUBLE tmp;
tmp=va_arg(argptr, _CRT_DOUBLE);
/* Note: assumes ch is in ASCII range */
/* In safecrt, we provide a special version of _cfltcvt which internally calls printf (see safecrt_output_s.c) */
_CFLTCVT(&tmp, buffer.sz, buffersize, (char)ch, precision, capexp);
/* check if result was negative, save '-' for later */
/* and point to positive part (this is for '0' padding) */
if (*text.sz == '-') {
flags |= FL_NEGATIVE;
++text.sz;
}
textlen = (int)strlen(text.sz); /* compute length of text */
}
break;
case _T('d'):
case _T('i'):
/* signed decimal output */
flags |= FL_SIGNED;
radix = 10;
goto COMMON_INT;
case _T('u'):
radix = 10;
goto COMMON_INT;
case _T('p'):
/* write a pointer -- this is like an integer or long */
/* except we force precision to pad with zeros and */
/* output in big hex. */
precision = 2 * sizeof(void *); /* number of hex digits needed */
#if PTR_IS_INT64
if (flags & (FL_LONG | FL_SHORT))
{
/* %lp, %Lp or %hp - these print 8 hex digits*/
precision = 2 * sizeof(int32_t);
}
else
{
flags |= FL_I64; /* assume we're converting an int64 */
}
#elif !PTR_IS_INT
flags |= FL_LONG; /* assume we're converting a long */
#endif /* !PTR_IS_INT */
/* DROP THROUGH to hex formatting */
FALLTHROUGH;
case _T('X'):
/* unsigned upper hex output */
hexadd = _T('A') - _T('9') - 1; /* set hexadd for uppercase hex */
goto COMMON_HEX;
case _T('x'):
/* unsigned lower hex output */
hexadd = _T('a') - _T('9') - 1; /* set hexadd for lowercase hex */
/* DROP THROUGH TO COMMON_HEX */
COMMON_HEX:
radix = 16;
if (flags & FL_ALTERNATE) {
/* alternate form means '0x' prefix */
prefix[0] = _T('0');
prefix[1] = (TCHAR)(_T('x') - _T('a') + _T('9') + 1 + hexadd); /* 'x' or 'X' */
prefixlen = 2;
}
goto COMMON_INT;
case _T('o'):
/* unsigned octal output */
radix = 8;
if (flags & FL_ALTERNATE) {
/* alternate form means force a leading 0 */
flags |= FL_FORCEOCTAL;
}
/* DROP THROUGH to COMMON_INT */
COMMON_INT: {
/* This is the general integer formatting routine. */
/* Basically, we get an argument, make it positive */
/* if necessary, and convert it according to the */
/* correct radix, setting text and textlen */
/* appropriately. */
#if _INTEGRAL_MAX_BITS >= 64
uint64_t number; /* number to convert */
int digit; /* ascii value of digit */
__int64 l; /* temp long value */
#else /* _INTEGRAL_MAX_BITS >= 64 */
unsigned long number; /* number to convert */
int digit; /* ascii value of digit */
long l; /* temp long value */
#endif /* _INTEGRAL_MAX_BITS >= 64 */
/* 1. read argument into l, sign extend as needed */
#if _INTEGRAL_MAX_BITS >= 64
if (flags & FL_I64)
l = get_int64_arg(&argptr);
else
#endif /* _INTEGRAL_MAX_BITS >= 64 */
if (flags & FL_LONGLONG)
l = get_long_long_arg(&argptr);
else
#if !LONG_IS_INT
if (flags & FL_LONG)
l = get_long_arg(&argptr);
else
#endif /* !LONG_IS_INT */
#if !SHORT_IS_INT
if (flags & FL_SHORT) {
if (flags & FL_SIGNED)
l = (short) get_int_arg(&argptr); /* sign extend */
else
l = (unsigned short) get_int_arg(&argptr); /* zero-extend*/
} else
#endif /* !SHORT_IS_INT */
{
if (flags & FL_SIGNED)
l = get_int_arg(&argptr); /* sign extend */
else
l = (unsigned int) get_int_arg(&argptr); /* zero-extend*/
}
/* 2. check for negative; copy into number */
if ( (flags & FL_SIGNED) && l < 0) {
number = -l;
flags |= FL_NEGATIVE; /* remember negative sign */
} else {
number = l;
}
#if _INTEGRAL_MAX_BITS >= 64
if ( (flags & FL_I64) == 0 && (flags & FL_LONGLONG) == 0 ) {
/*
* Unless printing a full 64-bit value, insure values
* here are not in cananical longword format to prevent
* the sign extended upper 32-bits from being printed.
*/
number &= 0xffffffff;
}
#endif /* _INTEGRAL_MAX_BITS >= 64 */
/* 3. check precision value for default; non-default */
/* turns off 0 flag, according to ANSI. */
if (precision < 0)
precision = 1; /* default precision */
else {
flags &= ~FL_LEADZERO;
if (precision > MAXPRECISION)
precision = MAXPRECISION;
}
/* 4. Check if data is 0; if so, turn off hex prefix */
if (number == 0)
prefixlen = 0;
/* 5. Convert data to ASCII -- note if precision is zero */
/* and number is zero, we get no digits at all. */
char *sz;
sz = &buffer.sz[BUFFERSIZE-1]; /* last digit at end of buffer */
while (precision-- > 0 || number != 0) {
digit = (int)(number % radix) + '0';
number /= radix; /* reduce number */
if (digit > '9') {
/* a hex digit, make it a letter */
digit += hexadd;
}
*sz-- = (char)digit; /* store the digit */
}
textlen = (int)((char *)&buffer.sz[BUFFERSIZE-1] - sz); /* compute length of number */
++sz; /* text points to first digit now */
/* 6. Force a leading zero if FORCEOCTAL flag set */
if ((flags & FL_FORCEOCTAL) && (textlen == 0 || sz[0] != '0')) {
*--sz = '0';
++textlen; /* add a zero */
}
text.sz = sz;
}
break;
}
/* At this point, we have done the specific conversion, and */
/* 'text' points to text to print; 'textlen' is length. Now we */
/* justify it, put on prefixes, leading zeros, and then */
/* print it. */
if (!no_output) {
int padding; /* amount of padding, negative means zero */
if (flags & FL_SIGNED) {
if (flags & FL_NEGATIVE) {
/* prefix is a '-' */
prefix[0] = _T('-');
prefixlen = 1;
}
else if (flags & FL_SIGN) {
/* prefix is '+' */
prefix[0] = _T('+');
prefixlen = 1;
}
else if (flags & FL_SIGNSP) {
/* prefix is ' ' */
prefix[0] = _T(' ');
prefixlen = 1;
}
}
/* calculate amount of padding -- might be negative, */
/* but this will just mean zero */
padding = fldwidth - textlen - prefixlen;
/* put out the padding, prefix, and text, in the correct order */
if (!(flags & (FL_LEFT | FL_LEADZERO))) {
/* pad on left with blanks */
WRITE_MULTI_CHAR(_T(' '), padding, &charsout);
}
/* write prefix */
WRITE_STRING(prefix, prefixlen, &charsout);
if ((flags & FL_LEADZERO) && !(flags & FL_LEFT)) {
/* write leading zeros */
WRITE_MULTI_CHAR(_T('0'), padding, &charsout);
}
/* write text */
#ifndef _UNICODE
if (bufferiswide && (textlen > 0)) {
const WCHAR *p;
int mbCharCount;
int count;
char mbStr[5];
p = text.wz;
count = textlen;
while (count-- > 0) {
mbCharCount = snprintf(mbStr, sizeof(mbStr), "%lc", *p);
if (mbCharCount == 0) {
charsout = -1;
break;
}
WRITE_STRING(mbStr, mbCharCount, &charsout);
p++;
}
} else {
WRITE_STRING(text.sz, textlen, &charsout);
}
#else /* _UNICODE */
if (!bufferiswide && textlen > 0) {
const char *p;
int retval = 0;
int count;
p = text.sz;
count = textlen;
while (count-- > 0) {
retval = _MBTOWC(&wchar, p, MB_CUR_MAX);
if (retval <= 0) {
charsout = -1;
break;
}
WRITE_CHAR(wchar, &charsout);
p += retval;
}
} else {
WRITE_STRING(text.wz, textlen, &charsout);
}
#endif /* _UNICODE */
if (charsout >= 0 && (flags & FL_LEFT)) {
/* pad on right with blanks */
WRITE_MULTI_CHAR(_T(' '), padding, &charsout);
}
/* we're done! */
}
break;
case ST_INVALID:
_VALIDATE_RETURN(0 /* FALSE */, EINVAL, -1);
break;
}
}
#ifdef FORMAT_VALIDATIONS
/* The format string shouldn't be incomplete - i.e. when we are finished
with the format string, the last thing we should have encountered
should have been a regular char to be output or a type specifier. Else
the format string was incomplete */
_VALIDATE_RETURN(((state == ST_NORMAL) || (state == ST_TYPE)), EINVAL, -1);
#endif /* FORMAT_VALIDATIONS */
return charsout; /* return value = number of characters written */
}
/*
* Future Optimizations for swprintf:
* - Don't free the memory used for converting the buffer to wide chars.
* Use realloc if the memory is not sufficient. Free it at the end.
*/
/***
*void write_char(char ch, int *pnumwritten)
*ifdef _UNICODE
*void write_char(char16_t ch, FILE *f, int *pnumwritten)
*endif
*void write_char(char ch, FILE *f, int *pnumwritten)
*
*Purpose:
* Writes a single character to the given file/console. If no error occurs,
* then *pnumwritten is incremented; otherwise, *pnumwritten is set
* to -1.
*
*Entry:
* _TCHAR ch - character to write
* FILE *f - file to write to
* int *pnumwritten - pointer to integer to update with total chars written
*
*Exit:
* No return value.
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
LOCAL(void) write_char (
_TCHAR ch,
int *pnumwritten
)
{
#ifdef _UNICODE
if (_putwch_nolock(ch) == WEOF)
#else /* _UNICODE */
if (_putch_nolock(ch) == EOF)
#endif /* _UNICODE */
*pnumwritten = -1;
else
++(*pnumwritten);
}
#else /* CPRFLAG */
LOCAL(void) write_char (
_TCHAR ch,
miniFILE *f,
int *pnumwritten
)
{
if ( (f->_flag & _IOSTRG) && f->_base == NULL)
{
++(*pnumwritten);
return;
}
#ifdef _UNICODE
if (_putwc_nolock(ch, f) == WEOF)
#else /* _UNICODE */
if (_putc_nolock(ch, f) == EOF)
#endif /* _UNICODE */
*pnumwritten = -1;
else
++(*pnumwritten);
}
#endif /* CPRFLAG */
/***
*void write_multi_char(char ch, int num, int *pnumwritten)
*ifdef _UNICODE
*void write_multi_char(char16_t ch, int num, FILE *f, int *pnumwritten)
*endif
*void write_multi_char(char ch, int num, FILE *f, int *pnumwritten)
*
*Purpose:
* Writes num copies of a character to the given file/console. If no error occurs,
* then *pnumwritten is incremented by num; otherwise, *pnumwritten is set
* to -1. If num is negative, it is treated as zero.
*
*Entry:
* _TCHAR ch - character to write
* int num - number of times to write the characters
* FILE *f - file to write to
* int *pnumwritten - pointer to integer to update with total chars written
*
*Exit:
* No return value.
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
LOCAL(void) write_multi_char (
_TCHAR ch,
int num,
int *pnumwritten
)
{
while (num-- > 0) {
write_char(ch, pnumwritten);
if (*pnumwritten == -1)
break;
}
}
#else /* CPRFLAG */
LOCAL(void) write_multi_char (
_TCHAR ch,
int num,
miniFILE *f,
int *pnumwritten
)
{
while (num-- > 0) {
write_char(ch, f, pnumwritten);
if (*pnumwritten == -1)
break;
}
}
#endif /* CPRFLAG */
/***
*void write_string(const char *string, int len, int *pnumwritten)
*void write_string(const char *string, int len, FILE *f, int *pnumwritten)
*ifdef _UNICODE
*void write_string(const char16_t *string, int len, FILE *f, int *pnumwritten)
*endif
*
*Purpose:
* Writes a string of the given length to the given file. If no error occurs,
* then *pnumwritten is incremented by len; otherwise, *pnumwritten is set
* to -1. If len is negative, it is treated as zero.
*
*Entry:
* _TCHAR *string - string to write (NOT null-terminated)
* int len - length of string
* FILE *f - file to write to
* int *pnumwritten - pointer to integer to update with total chars written
*
*Exit:
* No return value.
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
LOCAL(void) write_string (
const _TCHAR *string,
int len,
int *pnumwritten
)
{
while (len-- > 0) {
write_char(*string++, pnumwritten);
if (*pnumwritten == -1)
{
if (errno == EILSEQ)
write_char(_T('?'), pnumwritten);
else
break;
}
}
}
#else /* CPRFLAG */
LOCAL(void) write_string (
const _TCHAR *string,
int len,
miniFILE *f,
int *pnumwritten
)
{
if ( (f->_flag & _IOSTRG) && f->_base == NULL)
{
(*pnumwritten) += len;
return;
}
while (len-- > 0) {
write_char(*string++, f, pnumwritten);
if (*pnumwritten == -1)
{
if (errno == EILSEQ)
write_char(_T('?'), f, pnumwritten);
else
break;
}
}
}
#endif /* CPRFLAG */
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/***
*output.c - printf style output to a FILE
*
*
*Purpose:
* This file contains the code that does all the work for the
* printf family of functions. It should not be called directly, only
* by the *printf functions. We don't make any assumtions about the
* sizes of ints, longs, shorts, or long doubles, but if types do overlap,
* we also try to be efficient. We do assume that pointers are the same
* size as either ints or longs.
* If CPRFLAG is defined, defines _cprintf instead.
* **** DOESN'T CURRENTLY DO MTHREAD LOCKING ****
*
*Note:
* this file is included in safecrt.lib build directly, plese refer
* to safecrt_[w]output_s.c
*
*******************************************************************************/
//typedef __int64_t __int64;
#define FORMAT_VALIDATIONS
typedef double _CRT_DOUBLE;
//typedef int* intptr_t;
/*
Buffer size required to be passed to _gcvt, fcvt and other fp conversion routines
*/
#define _CVTBUFSIZE (309+40) /* # of digits in max. dp value + slop */
/* temporary work-around for compiler without 64-bit support */
#ifndef _INTEGRAL_MAX_BITS
#define _INTEGRAL_MAX_BITS 64
#endif /* _INTEGRAL_MAX_BITS */
//#include <mtdll.h>
//#include <cruntime.h>
//#include <limits.h>
//#include <string.h>
//#include <stddef.h>
//#include <crtdefs.h>
//#include <stdio.h>
//#include <stdarg.h>
//#include <cvt.h>
//#include <conio.h>
//#include <internal.h>
//#include <fltintrn.h>
//#include <stdlib.h>
//#include <ctype.h>
//#include <dbgint.h>
//#include <setlocal.h>
#define _MBTOWC(x,y,z) _minimal_chartowchar( x, y )
#ifndef _WCTOMB_S
#define _WCTOMB_S wctomb_s
#endif /* _WCTOMB_S */
#undef _malloc_crt
#define _malloc_crt malloc
#undef _free_crt
#define _free_crt free
#ifndef _CFLTCVT
#define _CFLTCVT _cfltcvt
#endif /* _CFLTCVT */
#ifndef _CLDCVT
#define _CLDCVT _cldcvt
#endif /* _CLDCVT */
/* this macro defines a function which is private and as fast as possible: */
/* for example, in C 6.0, it might be static _fastcall <type> near. */
#define LOCAL(x) static x __cdecl
/* int/long/short/pointer sizes */
/* the following should be set depending on the sizes of various types */
#if __LP64__
#define LONG_IS_INT 0
CASSERT(sizeof(long) > sizeof(int));
#else
#define LONG_IS_INT 1 /* 1 means long is same size as int */
CASSERT(sizeof(long) == sizeof(int));
#endif
#define SHORT_IS_INT 0 /* 1 means short is same size as int */
#define LONGLONG_IS_INT64 1 /* 1 means long long is same as int64 */
#if defined (HOST_64BIT)
#define PTR_IS_INT 0 /* 1 means ptr is same size as int */
CASSERT(sizeof(void *) != sizeof(int));
#if __LP64__
#define PTR_IS_LONG 1 /* 1 means ptr is same size as long */
CASSERT(sizeof(void *) == sizeof(long));
#else
#define PTR_IS_LONG 0 /* 1 means ptr is same size as long */
CASSERT(sizeof(void *) != sizeof(long));
#endif
#define PTR_IS_INT64 1 /* 1 means ptr is same size as int64 */
CASSERT(sizeof(void *) == sizeof(int64_t));
#else /* defined (HOST_64BIT) */
#define PTR_IS_INT 1 /* 1 means ptr is same size as int */
CASSERT(sizeof(void *) == sizeof(int));
#define PTR_IS_LONG 1 /* 1 means ptr is same size as long */
CASSERT(sizeof(void *) == sizeof(long));
#define PTR_IS_INT64 0 /* 1 means ptr is same size as int64 */
CASSERT(sizeof(void *) != sizeof(int64_t));
#endif /* defined (HOST_64BIT) */
/* CONSTANTS */
/* size of conversion buffer (ANSI-specified minimum is 509) */
#define BUFFERSIZE 512
#define MAXPRECISION BUFFERSIZE
#if BUFFERSIZE < _CVTBUFSIZE + 6
/*
* Buffer needs to be big enough for default minimum precision
* when converting floating point needs bigger buffer, and malloc
* fails
*/
#error Conversion buffer too small for max double.
#endif /* BUFFERSIZE < _CVTBUFSIZE + 6 */
/* flag definitions */
#define FL_SIGN 0x00001 /* put plus or minus in front */
#define FL_SIGNSP 0x00002 /* put space or minus in front */
#define FL_LEFT 0x00004 /* left justify */
#define FL_LEADZERO 0x00008 /* pad with leading zeros */
#define FL_LONG 0x00010 /* long value given */
#define FL_SHORT 0x00020 /* short value given */
#define FL_SIGNED 0x00040 /* signed data given */
#define FL_ALTERNATE 0x00080 /* alternate form requested */
#define FL_NEGATIVE 0x00100 /* value is negative */
#define FL_FORCEOCTAL 0x00200 /* force leading '0' for octals */
#define FL_LONGDOUBLE 0x00400 /* long double value given */
#define FL_WIDECHAR 0x00800 /* wide characters */
#define FL_LONGLONG 0x01000 /* long long value given */
#define FL_I64 0x08000 /* __int64 value given */
/* state definitions */
enum STATE {
ST_NORMAL, /* normal state; outputting literal chars */
ST_PERCENT, /* just read '%' */
ST_FLAG, /* just read flag character */
ST_WIDTH, /* just read width specifier */
ST_DOT, /* just read '.' */
ST_PRECIS, /* just read precision specifier */
ST_SIZE, /* just read size specifier */
ST_TYPE /* just read type specifier */
#ifdef FORMAT_VALIDATIONS
,ST_INVALID /* Invalid format */
#endif /* FORMAT_VALIDATIONS */
};
#ifdef FORMAT_VALIDATIONS
#define NUMSTATES (ST_INVALID + 1)
#else /* FORMAT_VALIDATIONS */
#define NUMSTATES (ST_TYPE + 1)
#endif /* FORMAT_VALIDATIONS */
/* character type values */
enum CHARTYPE {
CH_OTHER, /* character with no special meaning */
CH_PERCENT, /* '%' */
CH_DOT, /* '.' */
CH_STAR, /* '*' */
CH_ZERO, /* '0' */
CH_DIGIT, /* '1'..'9' */
CH_FLAG, /* ' ', '+', '-', '#' */
CH_SIZE, /* 'h', 'l', 'L', 'N', 'F', 'w' */
CH_TYPE /* type specifying character */
};
/* static data (read only, since we are re-entrant) */
//#if defined (_UNICODE) || defined (CPRFLAG) || defined (FORMAT_VALIDATIONS)
//extern const char __nullstring[]; /* string to print on null ptr */
//extern const char16_t __wnullstring[]; /* string to print on null ptr */
//#else /* defined (_UNICODE) || defined (CPRFLAG) || defined (FORMAT_VALIDATIONS) */
static const char __nullstring[] = "(null)"; /* string to print on null ptr */
static const char16_t __wnullstring[] = {'(', 'n', 'u', 'l', 'l', ')', '\0'};/* string to print on null ptr */
//#endif /* defined (_UNICODE) || defined (CPRFLAG) || defined (FORMAT_VALIDATIONS) */
/* The state table. This table is actually two tables combined into one. */
/* The lower nybble of each byte gives the character class of any */
/* character; while the uper nybble of the byte gives the next state */
/* to enter. See the macros below the table for details. */
/* */
/* The table is generated by maketabc.c -- use this program to make */
/* changes. */
#ifndef FORMAT_VALIDATIONS
//#if defined (_UNICODE) || defined (CPRFLAG)
//extern const char __lookuptable[];
//#else /* defined (_UNICODE) || defined (CPRFLAG) */
extern const char __lookuptable[] = {
/* ' ' */ 0x06,
/* '!' */ 0x00,
/* '"' */ 0x00,
/* '#' */ 0x06,
/* '$' */ 0x00,
/* '%' */ 0x01,
/* '&' */ 0x00,
/* ''' */ 0x00,
/* '(' */ 0x10,
/* ')' */ 0x00,
/* '*' */ 0x03,
/* '+' */ 0x06,
/* ',' */ 0x00,
/* '-' */ 0x06,
/* '.' */ 0x02,
/* '/' */ 0x10,
/* '0' */ 0x04,
/* '1' */ 0x45,
/* '2' */ 0x45,
/* '3' */ 0x45,
/* '4' */ 0x05,
/* '5' */ 0x05,
/* '6' */ 0x05,
/* '7' */ 0x05,
/* '8' */ 0x05,
/* '9' */ 0x35,
/* ':' */ 0x30,
/* ';' */ 0x00,
/* '<' */ 0x50,
/* '=' */ 0x00,
/* '>' */ 0x00,
/* '?' */ 0x00,
/* '@' */ 0x00,
/* 'A' */ 0x20, // Disable %A format
/* 'B' */ 0x20,
/* 'C' */ 0x38,
/* 'D' */ 0x50,
/* 'E' */ 0x58,
/* 'F' */ 0x07,
/* 'G' */ 0x08,
/* 'H' */ 0x00,
/* 'I' */ 0x37,
/* 'J' */ 0x30,
/* 'K' */ 0x30,
/* 'L' */ 0x57,
/* 'M' */ 0x50,
/* 'N' */ 0x07,
/* 'O' */ 0x00,
/* 'P' */ 0x00,
/* 'Q' */ 0x20,
/* 'R' */ 0x20,
/* 'S' */ 0x08,
/* 'T' */ 0x00,
/* 'U' */ 0x00,
/* 'V' */ 0x00,
/* 'W' */ 0x00,
/* 'X' */ 0x08,
/* 'Y' */ 0x60,
/* 'Z' */ 0x68,
/* '[' */ 0x60,
/* '\' */ 0x60,
/* ']' */ 0x60,
/* '^' */ 0x60,
/* '_' */ 0x00,
/* '`' */ 0x00,
/* 'a' */ 0x70, // Disable %a format
/* 'b' */ 0x70,
/* 'c' */ 0x78,
/* 'd' */ 0x78,
/* 'e' */ 0x78,
/* 'f' */ 0x78,
/* 'g' */ 0x08,
/* 'h' */ 0x07,
/* 'i' */ 0x08,
/* 'j' */ 0x00,
/* 'k' */ 0x00,
/* 'l' */ 0x07,
/* 'm' */ 0x00,
/* 'n' */ 0x00, // Disable %n format
/* 'o' */ 0x08,
/* 'p' */ 0x08,
/* 'q' */ 0x00,
/* 'r' */ 0x00,
/* 's' */ 0x08,
/* 't' */ 0x00,
/* 'u' */ 0x08,
/* 'v' */ 0x00,
/* 'w' */ 0x07,
/* 'x' */ 0x08
};
//#endif /* defined (_UNICODE) || defined (CPRFLAG) */
#else /* FORMAT_VALIDATIONS */
//#if defined (_UNICODE) || defined (CPRFLAG)
//extern const unsigned char __lookuptable_s[];
//#else /* defined (_UNICODE) || defined (CPRFLAG) */
static const unsigned char __lookuptable_s[] = {
/* ' ' */ 0x06,
/* '!' */ 0x80,
/* '"' */ 0x80,
/* '#' */ 0x86,
/* '$' */ 0x80,
/* '%' */ 0x81,
/* '&' */ 0x80,
/* ''' */ 0x00,
/* '(' */ 0x00,
/* ')' */ 0x10,
/* '*' */ 0x03,
/* '+' */ 0x86,
/* ',' */ 0x80,
/* '-' */ 0x86,
/* '.' */ 0x82,
/* '/' */ 0x80,
/* '0' */ 0x14,
/* '1' */ 0x05,
/* '2' */ 0x05,
/* '3' */ 0x45,
/* '4' */ 0x45,
/* '5' */ 0x45,
/* '6' */ 0x85,
/* '7' */ 0x85,
/* '8' */ 0x85,
/* '9' */ 0x05,
/* ':' */ 0x00,
/* ';' */ 0x00,
/* '<' */ 0x30,
/* '=' */ 0x30,
/* '>' */ 0x80,
/* '?' */ 0x50,
/* '@' */ 0x80,
/* 'A' */ 0x80, // Disable %A format
/* 'B' */ 0x00,
/* 'C' */ 0x08,
/* 'D' */ 0x00,
/* 'E' */ 0x28,
/* 'F' */ 0x27,
/* 'G' */ 0x38,
/* 'H' */ 0x50,
/* 'I' */ 0x57,
/* 'J' */ 0x80,
/* 'K' */ 0x00,
/* 'L' */ 0x07,
/* 'M' */ 0x00,
/* 'N' */ 0x37,
/* 'O' */ 0x30,
/* 'P' */ 0x30,
/* 'Q' */ 0x50,
/* 'R' */ 0x50,
/* 'S' */ 0x88,
/* 'T' */ 0x00,
/* 'U' */ 0x00,
/* 'V' */ 0x00,
/* 'W' */ 0x20,
/* 'X' */ 0x28,
/* 'Y' */ 0x80,
/* 'Z' */ 0x88,
/* '[' */ 0x80,
/* '\' */ 0x80,
/* ']' */ 0x00,
/* '^' */ 0x00,
/* '_' */ 0x00,
/* '`' */ 0x60,
/* 'a' */ 0x60, // Disable %a format
/* 'b' */ 0x60,
/* 'c' */ 0x68,
/* 'd' */ 0x68,
/* 'e' */ 0x68,
/* 'f' */ 0x08,
/* 'g' */ 0x08,
/* 'h' */ 0x07,
/* 'i' */ 0x78,
/* 'j' */ 0x70,
/* 'k' */ 0x70,
/* 'l' */ 0x77,
/* 'm' */ 0x70,
/* 'n' */ 0x70,
/* 'o' */ 0x08,
/* 'p' */ 0x08,
/* 'q' */ 0x00,
/* 'r' */ 0x00,
/* 's' */ 0x08,
/* 't' */ 0x00,
/* 'u' */ 0x08,
/* 'v' */ 0x00,
/* 'w' */ 0x07,
/* 'x' */ 0x08
};
//#endif /* defined (_UNICODE) || defined (CPRFLAG) */
#endif /* FORMAT_VALIDATIONS */
#define FIND_CHAR_CLASS(lookuptbl, c) \
((c) < _T(' ') || (c) > _T('x') ? \
CH_OTHER \
: \
(enum CHARTYPE)(lookuptbl[(c)-_T(' ')] & 0xF))
#define FIND_NEXT_STATE(lookuptbl, class, state) \
(enum STATE)(lookuptbl[(class) * NUMSTATES + (state)] >> 4)
/*
* Note: CPRFLAG and _UNICODE cases are currently mutually exclusive.
*/
/* prototypes */
#ifdef CPRFLAG
#define WRITE_CHAR(ch, pnw) write_char(ch, pnw)
#define WRITE_MULTI_CHAR(ch, num, pnw) write_multi_char(ch, num, pnw)
#define WRITE_STRING(s, len, pnw) write_string(s, len, pnw)
LOCAL(void) write_char(_TCHAR ch, int *pnumwritten);
LOCAL(void) write_multi_char(_TCHAR ch, int num, int *pnumwritten);
LOCAL(void) write_string(const _TCHAR *string, int len, int *numwritten);
#else /* CPRFLAG */
#define WRITE_CHAR(ch, pnw) write_char(ch, stream, pnw)
#define WRITE_MULTI_CHAR(ch, num, pnw) write_multi_char(ch, num, stream, pnw)
#define WRITE_STRING(s, len, pnw) write_string(s, len, stream, pnw)
LOCAL(void) write_char(_TCHAR ch, miniFILE *f, int *pnumwritten);
LOCAL(void) write_multi_char(_TCHAR ch, int num, miniFILE *f, int *pnumwritten);
LOCAL(void) write_string(const _TCHAR *string, int len, miniFILE *f, int *numwritten);
#endif /* CPRFLAG */
#define get_int_arg(list) va_arg(*list, int)
#define get_long_arg(list) va_arg(*list, long)
#define get_long_long_arg(list) va_arg(*list, long long)
#define get_int64_arg(list) va_arg(*list, __int64)
#define get_crtdouble_arg(list) va_arg(*list, _CRT_DOUBLE)
#define get_ptr_arg(list) va_arg(*list, void *)
#ifdef CPRFLAG
LOCAL(int) output(const _TCHAR *, _locale_t , va_list);
_CRTIMP int __cdecl _vtcprintf_l (const _TCHAR *, _locale_t, va_list);
_CRTIMP int __cdecl _vtcprintf_s_l (const _TCHAR *, _locale_t, va_list);
_CRTIMP int __cdecl _vtcprintf_p_l (const _TCHAR *, _locale_t, va_list);
/***
*int _cprintf(format, arglist) - write formatted output directly to console
*
*Purpose:
* Writes formatted data like printf, but uses console I/O functions.
*
*Entry:
* char *format - format string to determine data formats
* arglist - list of POINTERS to where to put data
*
*Exit:
* returns number of characters written
*
*Exceptions:
*
*******************************************************************************/
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _tcprintf_l (
const _TCHAR * format,
_locale_t plocinfo,
...
)
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _tcprintf_s_l (
const _TCHAR * format,
_locale_t plocinfo,
...
)
#endif /* FORMAT_VALIDATIONS */
{
int ret;
va_list arglist;
va_start(arglist, plocinfo);
#ifndef FORMAT_VALIDATIONS
ret = _vtcprintf_l(format, plocinfo, arglist);
#else /* FORMAT_VALIDATIONS */
ret = _vtcprintf_s_l(format, plocinfo, arglist);
#endif /* FORMAT_VALIDATIONS */
va_end(arglist);
return ret;
}
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _tcprintf (
const _TCHAR * format,
...
)
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _tcprintf_s (
const _TCHAR * format,
...
)
#endif /* FORMAT_VALIDATIONS */
{
int ret;
va_list arglist;
va_start(arglist, format);
#ifndef FORMAT_VALIDATIONS
ret = _vtcprintf_l(format, NULL, arglist);
#else /* FORMAT_VALIDATIONS */
ret = _vtcprintf_s_l(format, NULL, arglist);
#endif /* FORMAT_VALIDATIONS */
va_end(arglist);
return ret;
}
#endif /* CPRFLAG */
/***
*int _output(stream, format, argptr), static int output(format, argptr)
*
*Purpose:
* Output performs printf style output onto a stream. It is called by
* printf/fprintf/sprintf/vprintf/vfprintf/vsprintf to so the dirty
* work. In multi-thread situations, _output assumes that the given
* stream is already locked.
*
* Algorithm:
* The format string is parsed by using a finite state automaton
* based on the current state and the current character read from
* the format string. Thus, looping is on a per-character basis,
* not a per conversion specifier basis. Once the format specififying
* character is read, output is performed.
*
*Entry:
* FILE *stream - stream for output
* char *format - printf style format string
* va_list argptr - pointer to list of subsidiary arguments
*
*Exit:
* Returns the number of characters written, or -1 if an output error
* occurs.
*ifdef _UNICODE
* The wide-character flavour returns the number of wide-characters written.
*endif
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _vtcprintf (
const _TCHAR *format,
va_list argptr
)
{
return _vtcprintf_l(format, NULL, argptr);
}
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _vtcprintf_s (
const _TCHAR *format,
va_list argptr
)
{
return _vtcprintf_s_l(format, NULL, argptr);
}
#endif /* FORMAT_VALIDATIONS */
#endif /* CPRFLAG */
#ifdef CPRFLAG
#ifndef FORMAT_VALIDATIONS
_CRTIMP int __cdecl _vtcprintf_l (
#else /* FORMAT_VALIDATIONS */
_CRTIMP int __cdecl _vtcprintf_s_l (
#endif /* FORMAT_VALIDATIONS */
#else /* CPRFLAG */
#ifdef _UNICODE
#ifndef FORMAT_VALIDATIONS
int __cdecl _woutput (
miniFILE *stream,
#else /* FORMAT_VALIDATIONS */
int __cdecl _woutput_s (
miniFILE *stream,
#endif /* FORMAT_VALIDATIONS */
#else /* _UNICODE */
#ifndef FORMAT_VALIDATIONS
int __cdecl _output (
miniFILE *stream,
#else /* FORMAT_VALIDATIONS */
int __cdecl _output_s (
miniFILE *stream,
#endif /* FORMAT_VALIDATIONS */
#endif /* _UNICODE */
#endif /* CPRFLAG */
const _TCHAR *format,
va_list argptr
)
{
int hexadd=0; /* offset to add to number to get 'a'..'f' */
TCHAR ch; /* character just read */
int flags=0; /* flag word -- see #defines above for flag values */
enum STATE state; /* current state */
enum CHARTYPE chclass; /* class of current character */
int radix; /* current conversion radix */
int charsout; /* characters currently written so far, -1 = IO error */
int fldwidth = 0; /* selected field width -- 0 means default */
int precision = 0; /* selected precision -- -1 means default */
TCHAR prefix[2]; /* numeric prefix -- up to two characters */
int prefixlen=0; /* length of prefix -- 0 means no prefix */
int capexp = 0; /* non-zero = 'E' exponent signifient, zero = 'e' */
int no_output=0; /* non-zero = prodcue no output for this specifier */
union {
const char *sz; /* pointer text to be printed, not zero terminated */
const char16_t *wz;
} text;
int textlen; /* length of the text in bytes/wchars to be printed.
textlen is in multibyte or wide chars if _UNICODE */
union {
char sz[BUFFERSIZE];
#ifdef _UNICODE
char16_t wz[BUFFERSIZE];
#endif /* _UNICODE */
} buffer;
char16_t wchar; /* temp char16_t */
int buffersize; /* size of text.sz (used only for the call to _cfltcvt) */
int bufferiswide=0; /* non-zero = buffer contains wide chars already */
#ifndef CPRFLAG
_VALIDATE_RETURN( (stream != NULL), EINVAL, -1);
#endif /* CPRFLAG */
_VALIDATE_RETURN( (format != NULL), EINVAL, -1);
charsout = 0; /* no characters written yet */
textlen = 0; /* no text yet */
state = ST_NORMAL; /* starting state */
buffersize = 0;
/* main loop -- loop while format character exist and no I/O errors */
while ((ch = *format++) != _T('\0') && charsout >= 0) {
#ifndef FORMAT_VALIDATIONS
chclass = FIND_CHAR_CLASS(__lookuptable, ch); /* find character class */
state = FIND_NEXT_STATE(__lookuptable, chclass, state); /* find next state */
#else /* FORMAT_VALIDATIONS */
chclass = FIND_CHAR_CLASS(__lookuptable_s, ch); /* find character class */
state = FIND_NEXT_STATE(__lookuptable_s, chclass, state); /* find next state */
_VALIDATE_RETURN((state != ST_INVALID), EINVAL, -1);
#endif /* FORMAT_VALIDATIONS */
/* execute code for each state */
switch (state) {
case ST_NORMAL:
NORMAL_STATE:
/* normal state -- just write character */
#ifdef _UNICODE
bufferiswide = 1;
#else /* _UNICODE */
bufferiswide = 0;
#endif /* _UNICODE */
WRITE_CHAR(ch, &charsout);
break;
case ST_PERCENT:
/* set default value of conversion parameters */
prefixlen = fldwidth = no_output = capexp = 0;
flags = 0;
precision = -1;
bufferiswide = 0; /* default */
break;
case ST_FLAG:
/* set flag based on which flag character */
switch (ch) {
case _T('-'):
flags |= FL_LEFT; /* '-' => left justify */
break;
case _T('+'):
flags |= FL_SIGN; /* '+' => force sign indicator */
break;
case _T(' '):
flags |= FL_SIGNSP; /* ' ' => force sign or space */
break;
case _T('#'):
flags |= FL_ALTERNATE; /* '#' => alternate form */
break;
case _T('0'):
flags |= FL_LEADZERO; /* '0' => pad with leading zeros */
break;
}
break;
case ST_WIDTH:
/* update width value */
if (ch == _T('*')) {
/* get width from arg list */
fldwidth = get_int_arg(&argptr);
if (fldwidth < 0) {
/* ANSI says neg fld width means '-' flag and pos width */
flags |= FL_LEFT;
fldwidth = -fldwidth;
}
}
else {
/* add digit to current field width */
fldwidth = fldwidth * 10 + (ch - _T('0'));
}
break;
case ST_DOT:
/* zero the precision, since dot with no number means 0
not default, according to ANSI */
precision = 0;
break;
case ST_PRECIS:
/* update precison value */
if (ch == _T('*')) {
/* get precision from arg list */
precision = get_int_arg(&argptr);
if (precision < 0)
precision = -1; /* neg precision means default */
}
else {
/* add digit to current precision */
precision = precision * 10 + (ch - _T('0'));
}
break;
case ST_SIZE:
/* just read a size specifier, set the flags based on it */
switch (ch) {
case _T('l'):
/*
* In order to handle the ll case, we depart from the
* simple deterministic state machine.
*/
if (*format == _T('l'))
{
++format;
flags |= FL_LONGLONG; /* 'll' => long long */
}
else
{
flags |= FL_LONG; /* 'l' => long int or char16_t */
}
break;
case _T('L'):
if (*format == _T('p'))
{
flags |= FL_LONG;
}
break;
case _T('I'):
/*
* In order to handle the I, I32, and I64 size modifiers, we
* depart from the simple deterministic state machine. The
* code below scans for characters following the 'I',
* and defaults to 64 bit on WIN64 and 32 bit on WIN32
*/
#if PTR_IS_INT64
flags |= FL_I64; /* 'I' => __int64 on WIN64 systems */
#endif /* PTR_IS_INT64 */
if ( (*format == _T('6')) && (*(format + 1) == _T('4')) )
{
format += 2;
flags |= FL_I64; /* I64 => __int64 */
}
else if ( (*format == _T('3')) && (*(format + 1) == _T('2')) )
{
format += 2;
flags &= ~FL_I64; /* I32 => __int32 */
}
else if ( (*format == _T('d')) ||
(*format == _T('i')) ||
(*format == _T('o')) ||
(*format == _T('u')) ||
(*format == _T('x')) ||
(*format == _T('X')) )
{
/*
* Nothing further needed. %Id (et al) is
* handled just like %d, except that it defaults to 64 bits
* on WIN64. Fall through to the next iteration.
*/
}
else {
state = ST_NORMAL;
goto NORMAL_STATE;
}
break;
case _T('h'):
flags |= FL_SHORT; /* 'h' => short int or char */
break;
case _T('w'):
flags |= FL_WIDECHAR; /* 'w' => wide character */
break;
}
break;
case ST_TYPE:
/* we have finally read the actual type character, so we */
/* now format and "print" the output. We use a big switch */
/* statement that sets 'text' to point to the text that should */
/* be printed, and 'textlen' to the length of this text. */
/* Common code later on takes care of justifying it and */
/* other miscellaneous chores. Note that cases share code, */
/* in particular, all integer formatting is done in one place. */
/* Look at those funky goto statements! */
switch (ch) {
case _T('C'): /* ISO wide character */
if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
#ifdef _UNICODE
flags |= FL_SHORT;
#else /* _UNICODE */
flags |= FL_WIDECHAR; /* ISO std. */
#endif /* _UNICODE */
/* fall into 'c' case */
FALLTHROUGH;
case _T('c'): {
/* print a single character specified by int argument */
#ifdef _UNICODE
bufferiswide = 1;
wchar = (char16_t) get_int_arg(&argptr);
if (flags & FL_SHORT) {
/* format multibyte character */
/* this is an extension of ANSI */
char tempchar[2];
{
tempchar[0] = (char)(wchar & 0x00ff);
tempchar[1] = '\0';
}
if (_MBTOWC(buffer.wz,tempchar, MB_CUR_MAX) < 0)
{
/* ignore if conversion was unsuccessful */
no_output = 1;
}
} else {
buffer.wz[0] = wchar;
}
text.wz = buffer.wz;
textlen = 1; /* print just a single character */
#else /* _UNICODE */
if (flags & (FL_LONG|FL_WIDECHAR)) {
wchar = (char16_t) get_int_arg(&argptr);
textlen = snprintf(buffer.sz, BUFFERSIZE, "%lc", wchar);
if (textlen == 0)
{
no_output = 1;
}
} else {
/* format multibyte character */
/* this is an extension of ANSI */
unsigned short temp;
wchar = (char16_t)get_int_arg(&argptr);
temp = (unsigned short)wchar;
{
buffer.sz[0] = (char) temp;
textlen = 1;
}
}
text.sz = buffer.sz;
#endif /* _UNICODE */
}
break;
case _T('Z'): {
/* print a Counted String */
struct _count_string {
short Length;
short MaximumLength;
char *Buffer;
} *pstr;
pstr = (struct _count_string *)get_ptr_arg(&argptr);
if (pstr == NULL || pstr->Buffer == NULL) {
/* null ptr passed, use special string */
text.sz = __nullstring;
textlen = (int)strlen(text.sz);
} else {
if (flags & FL_WIDECHAR) {
text.wz = (char16_t *)pstr->Buffer;
textlen = pstr->Length / (int)sizeof(char16_t);
bufferiswide = 1;
} else {
bufferiswide = 0;
text.sz = pstr->Buffer;
textlen = pstr->Length;
}
}
}
break;
case _T('S'): /* ISO wide character string */
#ifndef _UNICODE
if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
flags |= FL_WIDECHAR;
#else /* _UNICODE */
if (!(flags & (FL_SHORT|FL_LONG|FL_WIDECHAR)))
flags |= FL_SHORT;
#endif /* _UNICODE */
FALLTHROUGH;
case _T('s'): {
/* print a string -- */
/* ANSI rules on how much of string to print: */
/* all if precision is default, */
/* min(precision, length) if precision given. */
/* prints '(null)' if a null string is passed */
int i;
const char *p; /* temps */
const char16_t *pwch;
/* At this point it is tempting to use strlen(), but */
/* if a precision is specified, we're not allowed to */
/* scan past there, because there might be no null */
/* at all. Thus, we must do our own scan. */
i = (precision == -1) ? INT_MAX : precision;
text.sz = (char *)get_ptr_arg(&argptr);
/* scan for null upto i characters */
#ifdef _UNICODE
if (flags & FL_SHORT) {
if (text.sz == NULL) /* NULL passed, use special string */
text.sz = __nullstring;
p = text.sz;
for (textlen=0; textlen<i && *p; textlen++) {
++p;
}
/* textlen now contains length in multibyte chars */
} else {
if (text.wz == NULL) /* NULL passed, use special string */
text.wz = __wnullstring;
bufferiswide = 1;
pwch = text.wz;
while (i-- && *pwch)
++pwch;
textlen = (int)(pwch - text.wz); /* in char16_ts */
/* textlen now contains length in wide chars */
}
#else /* _UNICODE */
if (flags & (FL_LONG|FL_WIDECHAR)) {
if (text.wz == NULL) /* NULL passed, use special string */
text.wz = __wnullstring;
bufferiswide = 1;
pwch = text.wz;
while ( i-- && *pwch )
++pwch;
textlen = (int)(pwch - text.wz);
/* textlen now contains length in wide chars */
} else {
if (text.sz == NULL) /* NULL passed, use special string */
text.sz = __nullstring;
p = text.sz;
while (i-- && *p)
++p;
textlen = (int)(p - text.sz); /* length of the string */
}
#endif /* _UNICODE */
}
break;
case _T('n'): {
/* write count of characters seen so far into */
/* short/int/long thru ptr read from args */
void *p; /* temp */
p = get_ptr_arg(&argptr);
/* %n is disabled */
_VALIDATE_RETURN(("'n' format specifier disabled" && 0), EINVAL, -1);
break;
/* store chars out into short/long/int depending on flags */
#if !LONG_IS_INT
if (flags & FL_LONG)
*(long *)p = charsout;
else
#endif /* !LONG_IS_INT */
#if !SHORT_IS_INT
if (flags & FL_SHORT)
*(short *)p = (short) charsout;
else
#endif /* !SHORT_IS_INT */
*(int *)p = charsout;
no_output = 1; /* force no output */
}
break;
case _T('E'):
case _T('G'):
case _T('A'):
capexp = 1; /* capitalize exponent */
ch += _T('a') - _T('A'); /* convert format char to lower */
FALLTHROUGH;
case _T('e'):
case _T('f'):
case _T('g'):
case _T('a'): {
/* floating point conversion -- we call cfltcvt routines */
/* to do the work for us. */
flags |= FL_SIGNED; /* floating point is signed conversion */
text.sz = buffer.sz; /* put result in buffer */
buffersize = BUFFERSIZE;
/* compute the precision value */
if (precision < 0)
precision = 6; /* default precision: 6 */
else if (precision == 0 && ch == _T('g'))
precision = 1; /* ANSI specified */
else if (precision > MAXPRECISION)
precision = MAXPRECISION;
if (precision > BUFFERSIZE - _CVTBUFSIZE) {
/* cap precision further */
precision = BUFFERSIZE - _CVTBUFSIZE;
}
/* for safecrt, we pass along the FL_ALTERNATE flag to _safecrt_cfltcvt */
if (flags & FL_ALTERNATE)
{
capexp |= FL_ALTERNATE;
}
_CRT_DOUBLE tmp;
tmp=va_arg(argptr, _CRT_DOUBLE);
/* Note: assumes ch is in ASCII range */
/* In safecrt, we provide a special version of _cfltcvt which internally calls printf (see safecrt_output_s.c) */
_CFLTCVT(&tmp, buffer.sz, buffersize, (char)ch, precision, capexp);
/* check if result was negative, save '-' for later */
/* and point to positive part (this is for '0' padding) */
if (*text.sz == '-') {
flags |= FL_NEGATIVE;
++text.sz;
}
textlen = (int)strlen(text.sz); /* compute length of text */
}
break;
case _T('d'):
case _T('i'):
/* signed decimal output */
flags |= FL_SIGNED;
radix = 10;
goto COMMON_INT;
case _T('u'):
radix = 10;
goto COMMON_INT;
case _T('p'):
/* write a pointer -- this is like an integer or long */
/* except we force precision to pad with zeros and */
/* output in big hex. */
precision = 2 * sizeof(void *); /* number of hex digits needed */
#if PTR_IS_INT64
if (flags & (FL_LONG | FL_SHORT))
{
/* %lp, %Lp or %hp - these print 8 hex digits*/
precision = 2 * sizeof(int32_t);
}
else
{
flags |= FL_I64; /* assume we're converting an int64 */
}
#elif !PTR_IS_INT
flags |= FL_LONG; /* assume we're converting a long */
#endif /* !PTR_IS_INT */
/* DROP THROUGH to hex formatting */
FALLTHROUGH;
case _T('X'):
/* unsigned upper hex output */
hexadd = _T('A') - _T('9') - 1; /* set hexadd for uppercase hex */
goto COMMON_HEX;
case _T('x'):
/* unsigned lower hex output */
hexadd = _T('a') - _T('9') - 1; /* set hexadd for lowercase hex */
/* DROP THROUGH TO COMMON_HEX */
COMMON_HEX:
radix = 16;
if (flags & FL_ALTERNATE) {
/* alternate form means '0x' prefix */
prefix[0] = _T('0');
prefix[1] = (TCHAR)(_T('x') - _T('a') + _T('9') + 1 + hexadd); /* 'x' or 'X' */
prefixlen = 2;
}
goto COMMON_INT;
case _T('o'):
/* unsigned octal output */
radix = 8;
if (flags & FL_ALTERNATE) {
/* alternate form means force a leading 0 */
flags |= FL_FORCEOCTAL;
}
/* DROP THROUGH to COMMON_INT */
COMMON_INT: {
/* This is the general integer formatting routine. */
/* Basically, we get an argument, make it positive */
/* if necessary, and convert it according to the */
/* correct radix, setting text and textlen */
/* appropriately. */
#if _INTEGRAL_MAX_BITS >= 64
uint64_t number; /* number to convert */
int digit; /* ascii value of digit */
__int64 l; /* temp long value */
#else /* _INTEGRAL_MAX_BITS >= 64 */
unsigned long number; /* number to convert */
int digit; /* ascii value of digit */
long l; /* temp long value */
#endif /* _INTEGRAL_MAX_BITS >= 64 */
/* 1. read argument into l, sign extend as needed */
#if _INTEGRAL_MAX_BITS >= 64
if (flags & FL_I64)
l = get_int64_arg(&argptr);
else
#endif /* _INTEGRAL_MAX_BITS >= 64 */
if (flags & FL_LONGLONG)
l = get_long_long_arg(&argptr);
else
#if !LONG_IS_INT
if (flags & FL_LONG)
l = get_long_arg(&argptr);
else
#endif /* !LONG_IS_INT */
#if !SHORT_IS_INT
if (flags & FL_SHORT) {
if (flags & FL_SIGNED)
l = (short) get_int_arg(&argptr); /* sign extend */
else
l = (unsigned short) get_int_arg(&argptr); /* zero-extend*/
} else
#endif /* !SHORT_IS_INT */
{
if (flags & FL_SIGNED)
l = get_int_arg(&argptr); /* sign extend */
else
l = (unsigned int) get_int_arg(&argptr); /* zero-extend*/
}
/* 2. check for negative; copy into number */
if ( (flags & FL_SIGNED) && l < 0) {
number = -l;
flags |= FL_NEGATIVE; /* remember negative sign */
} else {
number = l;
}
#if _INTEGRAL_MAX_BITS >= 64
if ( (flags & FL_I64) == 0 && (flags & FL_LONGLONG) == 0 ) {
/*
* Unless printing a full 64-bit value, insure values
* here are not in cananical longword format to prevent
* the sign extended upper 32-bits from being printed.
*/
number &= 0xffffffff;
}
#endif /* _INTEGRAL_MAX_BITS >= 64 */
/* 3. check precision value for default; non-default */
/* turns off 0 flag, according to ANSI. */
if (precision < 0)
precision = 1; /* default precision */
else {
flags &= ~FL_LEADZERO;
if (precision > MAXPRECISION)
precision = MAXPRECISION;
}
/* 4. Check if data is 0; if so, turn off hex prefix */
if (number == 0)
prefixlen = 0;
/* 5. Convert data to ASCII -- note if precision is zero */
/* and number is zero, we get no digits at all. */
char *sz;
sz = &buffer.sz[BUFFERSIZE-1]; /* last digit at end of buffer */
while (precision-- > 0 || number != 0) {
digit = (int)(number % radix) + '0';
number /= radix; /* reduce number */
if (digit > '9') {
/* a hex digit, make it a letter */
digit += hexadd;
}
*sz-- = (char)digit; /* store the digit */
}
textlen = (int)((char *)&buffer.sz[BUFFERSIZE-1] - sz); /* compute length of number */
++sz; /* text points to first digit now */
/* 6. Force a leading zero if FORCEOCTAL flag set */
if ((flags & FL_FORCEOCTAL) && (textlen == 0 || sz[0] != '0')) {
*--sz = '0';
++textlen; /* add a zero */
}
text.sz = sz;
}
break;
}
/* At this point, we have done the specific conversion, and */
/* 'text' points to text to print; 'textlen' is length. Now we */
/* justify it, put on prefixes, leading zeros, and then */
/* print it. */
if (!no_output) {
int padding; /* amount of padding, negative means zero */
if (flags & FL_SIGNED) {
if (flags & FL_NEGATIVE) {
/* prefix is a '-' */
prefix[0] = _T('-');
prefixlen = 1;
}
else if (flags & FL_SIGN) {
/* prefix is '+' */
prefix[0] = _T('+');
prefixlen = 1;
}
else if (flags & FL_SIGNSP) {
/* prefix is ' ' */
prefix[0] = _T(' ');
prefixlen = 1;
}
}
/* calculate amount of padding -- might be negative, */
/* but this will just mean zero */
padding = fldwidth - textlen - prefixlen;
/* put out the padding, prefix, and text, in the correct order */
if (!(flags & (FL_LEFT | FL_LEADZERO))) {
/* pad on left with blanks */
WRITE_MULTI_CHAR(_T(' '), padding, &charsout);
}
/* write prefix */
WRITE_STRING(prefix, prefixlen, &charsout);
if ((flags & FL_LEADZERO) && !(flags & FL_LEFT)) {
/* write leading zeros */
WRITE_MULTI_CHAR(_T('0'), padding, &charsout);
}
/* write text */
#ifndef _UNICODE
if (bufferiswide && (textlen > 0)) {
const WCHAR *p;
int mbCharCount;
int count;
char mbStr[5];
p = text.wz;
count = textlen;
while (count-- > 0) {
mbCharCount = snprintf(mbStr, sizeof(mbStr), "%lc", *p);
if (mbCharCount == 0) {
charsout = -1;
break;
}
WRITE_STRING(mbStr, mbCharCount, &charsout);
p++;
}
} else {
WRITE_STRING(text.sz, textlen, &charsout);
}
#else /* _UNICODE */
if (!bufferiswide && textlen > 0) {
const char *p;
int retval = 0;
int count;
p = text.sz;
count = textlen;
while (count-- > 0) {
retval = _MBTOWC(&wchar, p, MB_CUR_MAX);
if (retval <= 0) {
charsout = -1;
break;
}
WRITE_CHAR(wchar, &charsout);
p += retval;
}
} else {
WRITE_STRING(text.wz, textlen, &charsout);
}
#endif /* _UNICODE */
if (charsout >= 0 && (flags & FL_LEFT)) {
/* pad on right with blanks */
WRITE_MULTI_CHAR(_T(' '), padding, &charsout);
}
/* we're done! */
}
break;
case ST_INVALID:
_VALIDATE_RETURN(0 /* FALSE */, EINVAL, -1);
break;
}
}
#ifdef FORMAT_VALIDATIONS
/* The format string shouldn't be incomplete - i.e. when we are finished
with the format string, the last thing we should have encountered
should have been a regular char to be output or a type specifier. Else
the format string was incomplete */
_VALIDATE_RETURN(((state == ST_NORMAL) || (state == ST_TYPE)), EINVAL, -1);
#endif /* FORMAT_VALIDATIONS */
return charsout; /* return value = number of characters written */
}
/*
* Future Optimizations for swprintf:
* - Don't free the memory used for converting the buffer to wide chars.
* Use realloc if the memory is not sufficient. Free it at the end.
*/
/***
*void write_char(char ch, int *pnumwritten)
*ifdef _UNICODE
*void write_char(char16_t ch, FILE *f, int *pnumwritten)
*endif
*void write_char(char ch, FILE *f, int *pnumwritten)
*
*Purpose:
* Writes a single character to the given file/console. If no error occurs,
* then *pnumwritten is incremented; otherwise, *pnumwritten is set
* to -1.
*
*Entry:
* _TCHAR ch - character to write
* FILE *f - file to write to
* int *pnumwritten - pointer to integer to update with total chars written
*
*Exit:
* No return value.
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
LOCAL(void) write_char (
_TCHAR ch,
int *pnumwritten
)
{
#ifdef _UNICODE
if (_putwch_nolock(ch) == WEOF)
#else /* _UNICODE */
if (_putch_nolock(ch) == EOF)
#endif /* _UNICODE */
*pnumwritten = -1;
else
++(*pnumwritten);
}
#else /* CPRFLAG */
LOCAL(void) write_char (
_TCHAR ch,
miniFILE *f,
int *pnumwritten
)
{
if ( (f->_flag & _IOSTRG) && f->_base == NULL)
{
++(*pnumwritten);
return;
}
#ifdef _UNICODE
if (_putwc_nolock(ch, f) == WEOF)
#else /* _UNICODE */
if (_putc_nolock(ch, f) == EOF)
#endif /* _UNICODE */
*pnumwritten = -1;
else
++(*pnumwritten);
}
#endif /* CPRFLAG */
/***
*void write_multi_char(char ch, int num, int *pnumwritten)
*ifdef _UNICODE
*void write_multi_char(char16_t ch, int num, FILE *f, int *pnumwritten)
*endif
*void write_multi_char(char ch, int num, FILE *f, int *pnumwritten)
*
*Purpose:
* Writes num copies of a character to the given file/console. If no error occurs,
* then *pnumwritten is incremented by num; otherwise, *pnumwritten is set
* to -1. If num is negative, it is treated as zero.
*
*Entry:
* _TCHAR ch - character to write
* int num - number of times to write the characters
* FILE *f - file to write to
* int *pnumwritten - pointer to integer to update with total chars written
*
*Exit:
* No return value.
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
LOCAL(void) write_multi_char (
_TCHAR ch,
int num,
int *pnumwritten
)
{
while (num-- > 0) {
write_char(ch, pnumwritten);
if (*pnumwritten == -1)
break;
}
}
#else /* CPRFLAG */
LOCAL(void) write_multi_char (
_TCHAR ch,
int num,
miniFILE *f,
int *pnumwritten
)
{
while (num-- > 0) {
write_char(ch, f, pnumwritten);
if (*pnumwritten == -1)
break;
}
}
#endif /* CPRFLAG */
/***
*void write_string(const char *string, int len, int *pnumwritten)
*void write_string(const char *string, int len, FILE *f, int *pnumwritten)
*ifdef _UNICODE
*void write_string(const char16_t *string, int len, FILE *f, int *pnumwritten)
*endif
*
*Purpose:
* Writes a string of the given length to the given file. If no error occurs,
* then *pnumwritten is incremented by len; otherwise, *pnumwritten is set
* to -1. If len is negative, it is treated as zero.
*
*Entry:
* _TCHAR *string - string to write (NOT null-terminated)
* int len - length of string
* FILE *f - file to write to
* int *pnumwritten - pointer to integer to update with total chars written
*
*Exit:
* No return value.
*
*Exceptions:
*
*******************************************************************************/
#ifdef CPRFLAG
LOCAL(void) write_string (
const _TCHAR *string,
int len,
int *pnumwritten
)
{
while (len-- > 0) {
write_char(*string++, pnumwritten);
if (*pnumwritten == -1)
{
if (errno == EILSEQ)
write_char(_T('?'), pnumwritten);
else
break;
}
}
}
#else /* CPRFLAG */
LOCAL(void) write_string (
const _TCHAR *string,
int len,
miniFILE *f,
int *pnumwritten
)
{
if ( (f->_flag & _IOSTRG) && f->_base == NULL)
{
(*pnumwritten) += len;
return;
}
while (len-- > 0) {
write_char(*string++, f, pnumwritten);
if (*pnumwritten == -1)
{
if (errno == EILSEQ)
write_char(_T('?'), f, pnumwritten);
else
break;
}
}
}
#endif /* CPRFLAG */
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/DateType.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
Imports System
Imports System.Globalization
Imports Microsoft.VisualBasic.CompilerServices.Utils
Namespace Microsoft.VisualBasic.CompilerServices
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public NotInheritable Class DateType
' Prevent creation.
Private Sub New()
End Sub
Public Shared Function FromString(ByVal Value As String) As Date
Return DateType.FromString(Value, GetCultureInfo())
End Function
Public Shared Function FromString(ByVal Value As String, ByVal culture As Globalization.CultureInfo) As Date
Dim ParsedDate As System.DateTime
If TryParse(Value, ParsedDate) Then
Return ParsedDate
Else
'Truncate the string to 32 characters for the message
Throw New InvalidCastException(SR.Format(SR.InvalidCast_FromStringTo, Left(Value, 32), "Date"))
End If
End Function
Public Shared Function FromObject(ByVal Value As Object) As Date
If Value Is Nothing Then
Return Nothing
End If
Dim ValueInterface As IConvertible
Dim ValueTypeCode As TypeCode
ValueInterface = TryCast(Value, IConvertible)
If Not ValueInterface Is Nothing Then
ValueTypeCode = ValueInterface.GetTypeCode()
Select Case ValueTypeCode
Case TypeCode.DateTime
Return ValueInterface.ToDateTime(Nothing)
Case TypeCode.String
Return DateType.FromString(ValueInterface.ToString(Nothing), GetCultureInfo())
Case TypeCode.Boolean,
TypeCode.Byte,
TypeCode.Int16,
TypeCode.Int32,
TypeCode.Int64,
TypeCode.Single,
TypeCode.Double,
TypeCode.Decimal,
TypeCode.Char
' Fall through to error
Case Else
' Fall through to error
End Select
End If
Throw New InvalidCastException(SR.Format(SR.InvalidCast_FromTo, VBFriendlyName(Value), "Date"))
End Function
Friend Shared Function TryParse(ByVal Value As String, ByRef Result As System.DateTime) As Boolean
Const ParseStyle As DateTimeStyles =
DateTimeStyles.AllowWhiteSpaces Or
DateTimeStyles.NoCurrentDateDefault
Dim Culture As CultureInfo = GetCultureInfo()
Return System.DateTime.TryParse(ToHalfwidthNumbers(Value, Culture), Culture, ParseStyle, Result)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
Imports System
Imports System.Globalization
Imports Microsoft.VisualBasic.CompilerServices.Utils
Namespace Microsoft.VisualBasic.CompilerServices
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public NotInheritable Class DateType
' Prevent creation.
Private Sub New()
End Sub
Public Shared Function FromString(ByVal Value As String) As Date
Return DateType.FromString(Value, GetCultureInfo())
End Function
Public Shared Function FromString(ByVal Value As String, ByVal culture As Globalization.CultureInfo) As Date
Dim ParsedDate As System.DateTime
If TryParse(Value, ParsedDate) Then
Return ParsedDate
Else
'Truncate the string to 32 characters for the message
Throw New InvalidCastException(SR.Format(SR.InvalidCast_FromStringTo, Left(Value, 32), "Date"))
End If
End Function
Public Shared Function FromObject(ByVal Value As Object) As Date
If Value Is Nothing Then
Return Nothing
End If
Dim ValueInterface As IConvertible
Dim ValueTypeCode As TypeCode
ValueInterface = TryCast(Value, IConvertible)
If Not ValueInterface Is Nothing Then
ValueTypeCode = ValueInterface.GetTypeCode()
Select Case ValueTypeCode
Case TypeCode.DateTime
Return ValueInterface.ToDateTime(Nothing)
Case TypeCode.String
Return DateType.FromString(ValueInterface.ToString(Nothing), GetCultureInfo())
Case TypeCode.Boolean,
TypeCode.Byte,
TypeCode.Int16,
TypeCode.Int32,
TypeCode.Int64,
TypeCode.Single,
TypeCode.Double,
TypeCode.Decimal,
TypeCode.Char
' Fall through to error
Case Else
' Fall through to error
End Select
End If
Throw New InvalidCastException(SR.Format(SR.InvalidCast_FromTo, VBFriendlyName(Value), "Date"))
End Function
Friend Shared Function TryParse(ByVal Value As String, ByRef Result As System.DateTime) As Boolean
Const ParseStyle As DateTimeStyles =
DateTimeStyles.AllowWhiteSpaces Or
DateTimeStyles.NoCurrentDateDefault
Dim Culture As CultureInfo = GetCultureInfo()
Return System.DateTime.TryParse(ToHalfwidthNumbers(Value, Culture), Culture, ParseStyle, Result)
End Function
End Class
End Namespace
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/native/corehost/nethost/nethost.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef __NETHOST_H__
#define __NETHOST_H__
#include <stddef.h>
#ifdef _WIN32
#ifdef NETHOST_EXPORT
#define NETHOST_API __declspec(dllexport)
#else
// Consuming the nethost as a static library
// Shouldn't export attempt to dllimport.
#ifdef NETHOST_USE_AS_STATIC
#define NETHOST_API
#else
#define NETHOST_API __declspec(dllimport)
#endif
#endif
#define NETHOST_CALLTYPE __stdcall
#ifdef _WCHAR_T_DEFINED
typedef wchar_t char_t;
#else
typedef unsigned short char_t;
#endif
#else
#ifdef NETHOST_EXPORT
#define NETHOST_API __attribute__((__visibility__("default")))
#else
#define NETHOST_API
#endif
#define NETHOST_CALLTYPE
typedef char char_t;
#endif
#ifdef __cplusplus
extern "C" {
#endif
// Parameters for get_hostfxr_path
//
// Fields:
// size
// Size of the struct. This is used for versioning.
//
// assembly_path
// Path to the compenent's assembly.
// If specified, hostfxr is located as if the assembly_path is the apphost
//
// dotnet_root
// Path to directory containing the dotnet executable.
// If specified, hostfxr is located as if an application is started using
// 'dotnet app.dll', which means it will be searched for under the dotnet_root
// path and the assembly_path is ignored.
//
struct get_hostfxr_parameters {
size_t size;
const char_t *assembly_path;
const char_t *dotnet_root;
};
//
// Get the path to the hostfxr library
//
// Parameters:
// buffer
// Buffer that will be populated with the hostfxr path, including a null terminator.
//
// buffer_size
// [in] Size of buffer in char_t units.
// [out] Size of buffer used in char_t units. If the input value is too small
// or buffer is nullptr, this is populated with the minimum required size
// in char_t units for a buffer to hold the hostfxr path
//
// get_hostfxr_parameters
// Optional. Parameters that modify the behaviour for locating the hostfxr library.
// If nullptr, hostfxr is located using the enviroment variable or global registration
//
// Return value:
// 0 on success, otherwise failure
// 0x80008098 - buffer is too small (HostApiBufferTooSmall)
//
// Remarks:
// The full search for the hostfxr library is done on every call. To minimize the need
// to call this function multiple times, pass a large buffer (e.g. PATH_MAX).
//
NETHOST_API int NETHOST_CALLTYPE get_hostfxr_path(
char_t * buffer,
size_t * buffer_size,
const struct get_hostfxr_parameters *parameters);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // __NETHOST_H__
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef __NETHOST_H__
#define __NETHOST_H__
#include <stddef.h>
#ifdef _WIN32
#ifdef NETHOST_EXPORT
#define NETHOST_API __declspec(dllexport)
#else
// Consuming the nethost as a static library
// Shouldn't export attempt to dllimport.
#ifdef NETHOST_USE_AS_STATIC
#define NETHOST_API
#else
#define NETHOST_API __declspec(dllimport)
#endif
#endif
#define NETHOST_CALLTYPE __stdcall
#ifdef _WCHAR_T_DEFINED
typedef wchar_t char_t;
#else
typedef unsigned short char_t;
#endif
#else
#ifdef NETHOST_EXPORT
#define NETHOST_API __attribute__((__visibility__("default")))
#else
#define NETHOST_API
#endif
#define NETHOST_CALLTYPE
typedef char char_t;
#endif
#ifdef __cplusplus
extern "C" {
#endif
// Parameters for get_hostfxr_path
//
// Fields:
// size
// Size of the struct. This is used for versioning.
//
// assembly_path
// Path to the compenent's assembly.
// If specified, hostfxr is located as if the assembly_path is the apphost
//
// dotnet_root
// Path to directory containing the dotnet executable.
// If specified, hostfxr is located as if an application is started using
// 'dotnet app.dll', which means it will be searched for under the dotnet_root
// path and the assembly_path is ignored.
//
struct get_hostfxr_parameters {
size_t size;
const char_t *assembly_path;
const char_t *dotnet_root;
};
//
// Get the path to the hostfxr library
//
// Parameters:
// buffer
// Buffer that will be populated with the hostfxr path, including a null terminator.
//
// buffer_size
// [in] Size of buffer in char_t units.
// [out] Size of buffer used in char_t units. If the input value is too small
// or buffer is nullptr, this is populated with the minimum required size
// in char_t units for a buffer to hold the hostfxr path
//
// get_hostfxr_parameters
// Optional. Parameters that modify the behaviour for locating the hostfxr library.
// If nullptr, hostfxr is located using the enviroment variable or global registration
//
// Return value:
// 0 on success, otherwise failure
// 0x80008098 - buffer is too small (HostApiBufferTooSmall)
//
// Remarks:
// The full search for the hostfxr library is done on every call. To minimize the need
// to call this function multiple times, pass a large buffer (e.g. PATH_MAX).
//
NETHOST_API int NETHOST_CALLTYPE get_hostfxr_path(
char_t * buffer,
size_t * buffer_size,
const struct get_hostfxr_parameters *parameters);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // __NETHOST_H__
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/mono/mono/metadata/fdhandle.c |
#include "fdhandle.h"
#include "utils/mono-lazy-init.h"
#include "utils/mono-coop-mutex.h"
static GHashTable *fds;
static MonoCoopMutex fds_mutex;
static MonoFDHandleCallback fds_callback[MONO_FDTYPE_COUNT];
static mono_lazy_init_t fds_init = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
#ifndef DISABLE_ASSERT_MESSAGES
static const gchar *types_str[] = {
"File",
"Console",
"Pipe",
"Socket",
NULL
};
#endif
static void
fds_remove (gpointer data)
{
MonoFDHandle* fdhandle;
fdhandle = (MonoFDHandle*) data;
g_assert (fdhandle);
g_assert (fds_callback [fdhandle->type].close);
fds_callback [fdhandle->type].close (fdhandle);
mono_refcount_dec (fdhandle);
}
static void
initialize (void)
{
fds = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, fds_remove);
mono_coop_mutex_init (&fds_mutex);
}
void
mono_fdhandle_register (MonoFDType type, MonoFDHandleCallback *callback)
{
mono_lazy_initialize (&fds_init, initialize);
memcpy (&fds_callback [type], callback, sizeof (MonoFDHandleCallback));
}
static void
fdhandle_destroy (gpointer data)
{
MonoFDHandle* fdhandle;
fdhandle = (MonoFDHandle*) data;
g_assert (fdhandle);
g_assert (fds_callback [fdhandle->type].destroy);
fds_callback [fdhandle->type].destroy (fdhandle);
}
void
mono_fdhandle_init (MonoFDHandle *fdhandle, MonoFDType type, gint fd)
{
mono_refcount_init (fdhandle, fdhandle_destroy);
fdhandle->type = type;
fdhandle->fd = fd;
}
void
mono_fdhandle_insert (MonoFDHandle *fdhandle)
{
mono_coop_mutex_lock (&fds_mutex);
if (g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fdhandle->fd), NULL, NULL))
g_error("%s: duplicate %s fd %d", __func__, types_str [fdhandle->type], fdhandle->fd);
g_hash_table_insert (fds, GINT_TO_POINTER(fdhandle->fd), fdhandle);
mono_coop_mutex_unlock (&fds_mutex);
}
gboolean
mono_fdhandle_try_insert (MonoFDHandle *fdhandle)
{
mono_coop_mutex_lock (&fds_mutex);
if (g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fdhandle->fd), NULL, NULL)) {
/* we raced between 2 invocations of mono_fdhandle_try_insert */
mono_coop_mutex_unlock (&fds_mutex);
return FALSE;
}
g_hash_table_insert (fds, GINT_TO_POINTER(fdhandle->fd), fdhandle);
mono_coop_mutex_unlock (&fds_mutex);
return TRUE;
}
gboolean
mono_fdhandle_lookup_and_ref (gint fd, MonoFDHandle **fdhandle)
{
mono_coop_mutex_lock (&fds_mutex);
if (!g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fd), NULL, (gpointer*) fdhandle)) {
mono_coop_mutex_unlock (&fds_mutex);
return FALSE;
}
mono_refcount_inc (*fdhandle);
mono_coop_mutex_unlock (&fds_mutex);
return TRUE;
}
void
mono_fdhandle_unref (MonoFDHandle *fdhandle)
{
mono_refcount_dec (fdhandle);
}
gboolean
mono_fdhandle_close (gint fd)
{
MonoFDHandle *fdhandle;
gboolean removed;
mono_coop_mutex_lock (&fds_mutex);
if (!g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fd), NULL, (gpointer*) &fdhandle)) {
mono_coop_mutex_unlock (&fds_mutex);
return FALSE;
}
removed = g_hash_table_remove (fds, GINT_TO_POINTER(fdhandle->fd));
g_assert (removed);
mono_coop_mutex_unlock (&fds_mutex);
return TRUE;
}
|
#include "fdhandle.h"
#include "utils/mono-lazy-init.h"
#include "utils/mono-coop-mutex.h"
static GHashTable *fds;
static MonoCoopMutex fds_mutex;
static MonoFDHandleCallback fds_callback[MONO_FDTYPE_COUNT];
static mono_lazy_init_t fds_init = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
#ifndef DISABLE_ASSERT_MESSAGES
static const gchar *types_str[] = {
"File",
"Console",
"Pipe",
"Socket",
NULL
};
#endif
static void
fds_remove (gpointer data)
{
MonoFDHandle* fdhandle;
fdhandle = (MonoFDHandle*) data;
g_assert (fdhandle);
g_assert (fds_callback [fdhandle->type].close);
fds_callback [fdhandle->type].close (fdhandle);
mono_refcount_dec (fdhandle);
}
static void
initialize (void)
{
fds = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, fds_remove);
mono_coop_mutex_init (&fds_mutex);
}
void
mono_fdhandle_register (MonoFDType type, MonoFDHandleCallback *callback)
{
mono_lazy_initialize (&fds_init, initialize);
memcpy (&fds_callback [type], callback, sizeof (MonoFDHandleCallback));
}
static void
fdhandle_destroy (gpointer data)
{
MonoFDHandle* fdhandle;
fdhandle = (MonoFDHandle*) data;
g_assert (fdhandle);
g_assert (fds_callback [fdhandle->type].destroy);
fds_callback [fdhandle->type].destroy (fdhandle);
}
void
mono_fdhandle_init (MonoFDHandle *fdhandle, MonoFDType type, gint fd)
{
mono_refcount_init (fdhandle, fdhandle_destroy);
fdhandle->type = type;
fdhandle->fd = fd;
}
void
mono_fdhandle_insert (MonoFDHandle *fdhandle)
{
mono_coop_mutex_lock (&fds_mutex);
if (g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fdhandle->fd), NULL, NULL))
g_error("%s: duplicate %s fd %d", __func__, types_str [fdhandle->type], fdhandle->fd);
g_hash_table_insert (fds, GINT_TO_POINTER(fdhandle->fd), fdhandle);
mono_coop_mutex_unlock (&fds_mutex);
}
gboolean
mono_fdhandle_try_insert (MonoFDHandle *fdhandle)
{
mono_coop_mutex_lock (&fds_mutex);
if (g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fdhandle->fd), NULL, NULL)) {
/* we raced between 2 invocations of mono_fdhandle_try_insert */
mono_coop_mutex_unlock (&fds_mutex);
return FALSE;
}
g_hash_table_insert (fds, GINT_TO_POINTER(fdhandle->fd), fdhandle);
mono_coop_mutex_unlock (&fds_mutex);
return TRUE;
}
gboolean
mono_fdhandle_lookup_and_ref (gint fd, MonoFDHandle **fdhandle)
{
mono_coop_mutex_lock (&fds_mutex);
if (!g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fd), NULL, (gpointer*) fdhandle)) {
mono_coop_mutex_unlock (&fds_mutex);
return FALSE;
}
mono_refcount_inc (*fdhandle);
mono_coop_mutex_unlock (&fds_mutex);
return TRUE;
}
void
mono_fdhandle_unref (MonoFDHandle *fdhandle)
{
mono_refcount_dec (fdhandle);
}
gboolean
mono_fdhandle_close (gint fd)
{
MonoFDHandle *fdhandle;
gboolean removed;
mono_coop_mutex_lock (&fds_mutex);
if (!g_hash_table_lookup_extended (fds, GINT_TO_POINTER(fd), NULL, (gpointer*) &fdhandle)) {
mono_coop_mutex_unlock (&fds_mutex);
return FALSE;
}
removed = g_hash_table_remove (fds, GINT_TO_POINTER(fdhandle->fd));
g_assert (removed);
mono_coop_mutex_unlock (&fds_mutex);
return TRUE;
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/mono/mono/mini/tiered.c | #include <config.h>
#include <mono/utils/mono-compiler.h>
#include "mini.h"
#include "mini-runtime.h"
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-logger-internals.h>
#ifdef ENABLE_EXPERIMENT_TIERED
MiniTieredStats mini_tiered_stats;
static MonoCoopCond compilation_wait;
static MonoCoopMutex compilation_mutex;
#define NUM_TIERS 2
static GSList *compilation_queue [NUM_TIERS];
static CallsitePatcher patchers [NUM_TIERS] = { NULL };
static const char* const patch_kind_str[] = {
"INTERP",
"JIT",
};
static GHashTable *callsites_hash [TIERED_PATCH_KIND_NUM] = { NULL };
/* TODO: use scientific methods (TM) to determine values */
static const int threshold [NUM_TIERS] = {
1000, /* tier 0 */
3000, /* tier 1 */
};
static void
compiler_thread (void)
{
MonoInternalThread *internal = mono_thread_internal_current ();
internal->state |= ThreadState_Background;
internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
mono_native_thread_set_name (mono_native_thread_id_get (), "Tiered Compilation Thread");
while (TRUE) {
mono_coop_cond_wait (&compilation_wait, &compilation_mutex);
for (int tier_level = 0; tier_level < NUM_TIERS; tier_level++) {
GSList *ppcs = compilation_queue [tier_level];
compilation_queue [tier_level] = NULL;
for (GSList *ppc_= ppcs; ppc_ != NULL; ppc_ = ppc_->next) {
MiniTieredPatchPointContext *ppc = (MiniTieredPatchPointContext *) ppc_->data;
for (int patch_kind = 0; patch_kind < TIERED_PATCH_KIND_NUM; patch_kind++) {
if (!callsites_hash [patch_kind])
continue;
GSList *patchsites = g_hash_table_lookup (callsites_hash [patch_kind], ppc->target_method);
for (; patchsites != NULL; patchsites = patchsites->next) {
gpointer patchsite = (gpointer) patchsites->data;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "tiered: patching %p with patch_kind=%s @ tier_level=%d", patchsite, patch_kind_str [patch_kind], tier_level);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "\t-> caller=%s", mono_pmip (patchsite));
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "\t-> callee=%s", mono_method_full_name (ppc->target_method, TRUE));
gboolean success = patchers [patch_kind] (ppc, patchsite);
if (!success)
mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_TIERED, "tiered: couldn't patch %p with target %s, dropping it.", patchsite, mono_method_full_name (ppc->target_method, TRUE));
}
g_hash_table_remove (callsites_hash [patch_kind], ppc->target_method);
g_slist_free (patchsites);
}
g_free (ppc);
}
g_slist_free (ppcs);
}
mono_coop_mutex_unlock (&compilation_mutex);
}
}
void
mini_tiered_init (void)
{
ERROR_DECL (error);
mono_counters_init ();
mono_counters_register ("Methods promoted", MONO_COUNTER_TIERED | MONO_COUNTER_LONG, &mini_tiered_stats.methods_promoted);
mono_coop_cond_init (&compilation_wait);
mono_coop_mutex_init (&compilation_mutex);
mono_thread_create_internal ((MonoThreadStart)compiler_thread, NULL, MONO_THREAD_CREATE_FLAGS_THREADPOOL, error);
mono_error_assert_ok (error);
}
void
mini_tiered_register_callsite_patcher (CallsitePatcher func, int level)
{
g_assert (level < NUM_TIERS);
patchers [level] = func;
}
void
mini_tiered_record_callsite (gpointer ip, MonoMethod *target_method, int patch_kind)
{
if (!callsites_hash [patch_kind])
callsites_hash [patch_kind] = g_hash_table_new (NULL, NULL);
GSList *patchsites = g_hash_table_lookup (callsites_hash [patch_kind], target_method);
patchsites = g_slist_prepend (patchsites, ip);
g_hash_table_insert (callsites_hash [patch_kind], target_method, patchsites);
}
void
mini_tiered_inc (MonoMethod *method, MiniTieredCounter *tcnt, int tier_level)
{
if (G_UNLIKELY (tcnt->hotness == threshold [tier_level] && !tcnt->promoted)) {
tcnt->promoted = TRUE;
mini_tiered_stats.methods_promoted++;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "tiered: queued %s", mono_method_full_name (method, TRUE));
MiniTieredPatchPointContext *ppc = g_new0 (MiniTieredPatchPointContext, 1);
ppc->target_method = method;
ppc->tier_level = tier_level;
mono_coop_mutex_lock (&compilation_mutex);
compilation_queue [tier_level] = g_slist_append (compilation_queue [tier_level], ppc);
mono_coop_mutex_unlock (&compilation_mutex);
mono_coop_cond_signal (&compilation_wait);
} else if (!tcnt->promoted) {
/* FIXME: inline that into caller */
tcnt->hotness++;
}
}
#else
MONO_EMPTY_SOURCE_FILE (tiered);
#endif
| #include <config.h>
#include <mono/utils/mono-compiler.h>
#include "mini.h"
#include "mini-runtime.h"
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-logger-internals.h>
#ifdef ENABLE_EXPERIMENT_TIERED
MiniTieredStats mini_tiered_stats;
static MonoCoopCond compilation_wait;
static MonoCoopMutex compilation_mutex;
#define NUM_TIERS 2
static GSList *compilation_queue [NUM_TIERS];
static CallsitePatcher patchers [NUM_TIERS] = { NULL };
static const char* const patch_kind_str[] = {
"INTERP",
"JIT",
};
static GHashTable *callsites_hash [TIERED_PATCH_KIND_NUM] = { NULL };
/* TODO: use scientific methods (TM) to determine values */
static const int threshold [NUM_TIERS] = {
1000, /* tier 0 */
3000, /* tier 1 */
};
static void
compiler_thread (void)
{
MonoInternalThread *internal = mono_thread_internal_current ();
internal->state |= ThreadState_Background;
internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
mono_native_thread_set_name (mono_native_thread_id_get (), "Tiered Compilation Thread");
while (TRUE) {
mono_coop_cond_wait (&compilation_wait, &compilation_mutex);
for (int tier_level = 0; tier_level < NUM_TIERS; tier_level++) {
GSList *ppcs = compilation_queue [tier_level];
compilation_queue [tier_level] = NULL;
for (GSList *ppc_= ppcs; ppc_ != NULL; ppc_ = ppc_->next) {
MiniTieredPatchPointContext *ppc = (MiniTieredPatchPointContext *) ppc_->data;
for (int patch_kind = 0; patch_kind < TIERED_PATCH_KIND_NUM; patch_kind++) {
if (!callsites_hash [patch_kind])
continue;
GSList *patchsites = g_hash_table_lookup (callsites_hash [patch_kind], ppc->target_method);
for (; patchsites != NULL; patchsites = patchsites->next) {
gpointer patchsite = (gpointer) patchsites->data;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "tiered: patching %p with patch_kind=%s @ tier_level=%d", patchsite, patch_kind_str [patch_kind], tier_level);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "\t-> caller=%s", mono_pmip (patchsite));
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "\t-> callee=%s", mono_method_full_name (ppc->target_method, TRUE));
gboolean success = patchers [patch_kind] (ppc, patchsite);
if (!success)
mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_TIERED, "tiered: couldn't patch %p with target %s, dropping it.", patchsite, mono_method_full_name (ppc->target_method, TRUE));
}
g_hash_table_remove (callsites_hash [patch_kind], ppc->target_method);
g_slist_free (patchsites);
}
g_free (ppc);
}
g_slist_free (ppcs);
}
mono_coop_mutex_unlock (&compilation_mutex);
}
}
void
mini_tiered_init (void)
{
ERROR_DECL (error);
mono_counters_init ();
mono_counters_register ("Methods promoted", MONO_COUNTER_TIERED | MONO_COUNTER_LONG, &mini_tiered_stats.methods_promoted);
mono_coop_cond_init (&compilation_wait);
mono_coop_mutex_init (&compilation_mutex);
mono_thread_create_internal ((MonoThreadStart)compiler_thread, NULL, MONO_THREAD_CREATE_FLAGS_THREADPOOL, error);
mono_error_assert_ok (error);
}
void
mini_tiered_register_callsite_patcher (CallsitePatcher func, int level)
{
g_assert (level < NUM_TIERS);
patchers [level] = func;
}
void
mini_tiered_record_callsite (gpointer ip, MonoMethod *target_method, int patch_kind)
{
if (!callsites_hash [patch_kind])
callsites_hash [patch_kind] = g_hash_table_new (NULL, NULL);
GSList *patchsites = g_hash_table_lookup (callsites_hash [patch_kind], target_method);
patchsites = g_slist_prepend (patchsites, ip);
g_hash_table_insert (callsites_hash [patch_kind], target_method, patchsites);
}
void
mini_tiered_inc (MonoMethod *method, MiniTieredCounter *tcnt, int tier_level)
{
if (G_UNLIKELY (tcnt->hotness == threshold [tier_level] && !tcnt->promoted)) {
tcnt->promoted = TRUE;
mini_tiered_stats.methods_promoted++;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TIERED, "tiered: queued %s", mono_method_full_name (method, TRUE));
MiniTieredPatchPointContext *ppc = g_new0 (MiniTieredPatchPointContext, 1);
ppc->target_method = method;
ppc->tier_level = tier_level;
mono_coop_mutex_lock (&compilation_mutex);
compilation_queue [tier_level] = g_slist_append (compilation_queue [tier_level], ppc);
mono_coop_mutex_unlock (&compilation_mutex);
mono_coop_cond_signal (&compilation_wait);
} else if (!tcnt->promoted) {
/* FIXME: inline that into caller */
tcnt->hotness++;
}
}
#else
MONO_EMPTY_SOURCE_FILE (tiered);
#endif
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Win32ThreadPoolNativeOverlapped.ExecutionContextCallbackArgs.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Threading
{
internal partial struct Win32ThreadPoolNativeOverlapped
{
private unsafe class ExecutionContextCallbackArgs
{
internal uint _errorCode;
internal uint _bytesWritten;
internal Win32ThreadPoolNativeOverlapped* _overlapped;
internal OverlappedData _data;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Threading
{
internal partial struct Win32ThreadPoolNativeOverlapped
{
private unsafe class ExecutionContextCallbackArgs
{
internal uint _errorCode;
internal uint _bytesWritten;
internal Win32ThreadPoolNativeOverlapped* _overlapped;
internal OverlappedData _data;
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./src/tests/JIT/HardwareIntrinsics/General/Vector64/Narrow.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 NarrowDouble()
{
var test = new VectorBinaryOpTest__NarrowDouble();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__NarrowDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Double> _fld1;
public Vector64<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__NarrowDouble testClass)
{
var result = Vector64.Narrow(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector64<Double> _clsVar1;
private static Vector64<Double> _clsVar2;
private Vector64<Double> _fld1;
private Vector64<Double> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__NarrowDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
}
public VectorBinaryOpTest__NarrowDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Narrow(
Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Narrow), new Type[] {
typeof(Vector64<Double>),
typeof(Vector64<Double>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Narrow), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Single));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Narrow(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr);
var result = Vector64.Narrow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__NarrowDouble();
var result = Vector64.Narrow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Narrow(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Narrow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<Double> op1, Vector64<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (float)(left[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (float)((i < Op1ElementCount) ? left[i] : right[i - Op1ElementCount]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Narrow)}<Single>(Vector64<Double>, Vector64<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void NarrowDouble()
{
var test = new VectorBinaryOpTest__NarrowDouble();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__NarrowDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Double> _fld1;
public Vector64<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__NarrowDouble testClass)
{
var result = Vector64.Narrow(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector64<Double> _clsVar1;
private static Vector64<Double> _clsVar2;
private Vector64<Double> _fld1;
private Vector64<Double> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__NarrowDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
}
public VectorBinaryOpTest__NarrowDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Narrow(
Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Narrow), new Type[] {
typeof(Vector64<Double>),
typeof(Vector64<Double>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Narrow), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Single));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Narrow(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr);
var result = Vector64.Narrow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__NarrowDouble();
var result = Vector64.Narrow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Narrow(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Narrow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<Double> op1, Vector64<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (float)(left[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (float)((i < Op1ElementCount) ? left[i] : right[i - Op1ElementCount]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Narrow)}<Single>(Vector64<Double>, Vector64<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
|
dotnet/runtime | 66,025 | Move Array.CreateInstance methods to shared CoreLib | jkotas | 2022-03-01T20:10:54Z | 2022-03-09T15:56:10Z | 6187fdfad1cc8670454a80776f0ee6a43a979fba | f97788194aa647bf46c3c1e3b0526704dce15093 | Move Array.CreateInstance methods to shared CoreLib. | ./docs/design/coreclr/jit/images/ThreeClassesDevirt.JPG |